Java工程中動態改變Hibernate的數據庫連接信息總結

1、XML解析幫助類,採用Dom4j工具類進行處理

package com.cvicse.inforguard.cssp.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.xpath.DefaultXPath;


/**
 * 
 * 
 * 描述:<p>    讀取、重寫Hibernate配置文件的工具類。</p>
 * 創建日期:2012-6-27 上午9:59:49<br>
 * @author:tianyj<br> 
 * @update:$Date$<br>
 * @version:$Revision$<br>
 * @since 版本號,用來指定該類是從整個項目的哪個版本開始加入到項目中的
 */
public class ConfigHibernateHelper {
	
	private SAXReader reader = null;
	private File file = null;
	private String url = null;
	private Document document = null;
	private List<Element> nodeList = null;
	
	private XMLWriter writer = null;
	
	
	/**
	 * 讀取XML文件,返回根據過濾條件進行過濾的節點列表
	 * @param fileName 文件名稱
	 * @param xpath 過濾條件
	 * @return 節點元素列表
	 */
	public List<Element> read(String fileName, String pro_xpath, String map_xpath){
		reader = new SAXReader(); 
        try {
        	url = this.getFilePath(fileName);
        	file = new File(url);
            reader.setEntityResolver(new NoOpEntityResolver());
            document = reader.read(file);
            // 獲得hibernate-configuration:session-factory下的property屬性節點列表
            DefaultXPath propertyPath = new DefaultXPath(pro_xpath);
            nodeList = getNodeList(document, propertyPath);
            // 獲得hibernate-configuration:session-factory下的mapping屬性節點列表
            DefaultXPath mappingPath = new DefaultXPath(map_xpath);  
            List<Element> mappings = getNodeList(document, mappingPath);
            
            nodeList.addAll(mappings);
            
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return nodeList;
	}
	
	/**
	 * 根據條件返回節點列表
	 * @param document 文檔變量
	 * @param propertyPath 過濾條件對象
	 * @return
	 */
	@SuppressWarnings("unchecked")
    private List<Element> getNodeList(Document document, DefaultXPath propertyPath) {
	    return propertyPath.selectNodes(document);
    } 
	
	/**
	 * 返回配置文件的路徑
	 * @param fileName
	 * @return
	 */
	private String getFilePath(String fileName){
		return getClass().getClassLoader().getResource(fileName).getPath();
	}
	
	/**
	 * 替換從前臺傳遞的配置新的數據庫連接屬性
	 * @param paraMap 修改的數據key-value
	 * @param nodeList 節點列表
	 */
	public List<Element> replaceNewValue(Map<String,String> paraMap, List<Element> nodeList){
		// 循環需要修改的節點信息,從前臺進行傳遞過來
		for(Map.Entry<String, String> entry : paraMap.entrySet()){
			for (Element property : nodeList) {  
                String name = property.attributeValue("name");
                // 過濾掉Mapping配置文件節點
                String resource = property.attributeValue("resource");
                if(null != resource && "resource".equals(resource)){
                	break;
                }
                // 設置修改後的屬性值
                if(entry.getKey().equals(name)
                		|| entry.getKey().equals(name) || entry.getKey().equals(name)){
                	property.setText(entry.getValue());
                }
            }  
		}
		return nodeList;
	}
	
	/**
	 * 把配置信息從新寫入
	 * @param nodeList
	 * @param fileName
	 * @return
	 */
	public boolean write(String fileName, List<Element> nodeList){
		url = this.getFilePath(fileName);
		// document
		Document document = DocumentHelper.createDocument();
		// 設置DocType
		document.addDocType("hibernate-configuration" , 
				"-//Hibernate/Hibernate Configuration DTD 3.0//EN" , 
				"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
		// hibernate-configuration  
        Element configuration = document.addElement("hibernate-configuration");  
        // session-factory  
        Element sessionfactory = configuration.addElement("session-factory");  
        sessionfactory.addComment("Database connection settings");
        // 添加屬性
        for(Element property : nodeList){
        	String name = property.attributeValue("name");
        	String resource = property.attributeValue("resource");
        	String text = property.getText();
        	// property節點操作方式
        	if(null != name && null!=text && !"".equals(name) && !"".equals(text)){
        		Element proElement = sessionfactory.addElement("property");  
        		proElement.addAttribute("name", property.attributeValue("name").trim());  
        		proElement.setText(property.getText().trim());
        	}else if(null != resource && !"".equals(resource)){
        		// mapping節點操作方式
        		Element mapping = sessionfactory.addElement("mapping");
        		mapping.addAttribute("resource", property.attributeValue("resource").trim());
        	}
        	
        }
        
        //設置輸出格式  
        OutputFormat format = new OutputFormat();  
        format.setEncoding("utf-8");  
        format.setIndent(true);  
        format.setLineSeparator("\n");  
        format.setNewlines(true);
        
        try {  
            writer = new XMLWriter(format);  
            writer.setOutputStream(new FileOutputStream(url));  
            writer.write(document);  
            writer.flush();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if(writer != null) {  
                try {  
                    writer.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        } 
		return true;
	}
}

2、修改緩存中Configuration配置數據庫的信息

	/**
	 * 根據前臺傳遞的數據庫配置信息進行立即修改
	 * @param paraMap
	 * @throws EXP_Base
	 */
	public static void getConfiguration(Map<String, String> paraMap) throws EXP_Base{
		try {
			// 在Hibernate的緩存中移除數據庫URL、用戶名、密碼配置信息
			configuration.getProperties().remove(Constant.CONNECTION_URL);
			configuration.getProperties().remove(Constant.CONNECTION_USERNAME);
			configuration.getProperties().remove(Constant.CONNECTION_PASSWORD);
			// 在Hibernate的緩存中添加新的數據庫URL、用戶名、密碼配置信息
			configuration.getProperties().setProperty(
					Constant.CONNECTION_URL, paraMap.get(Constant.CONNECTION_URL));
			configuration.getProperties().setProperty(
					Constant.CONNECTION_USERNAME, paraMap.get(Constant.CONNECTION_USERNAME));
			configuration.getProperties().setProperty(
					Constant.CONNECTION_PASSWORD, paraMap.get(Constant.CONNECTION_PASSWORD));
			/*
			 * 銷燬SessionFactory並釋放所有資源(緩存,連接池等)。
			 */
			if (sessionFactory != null) {
				sessionFactory.close();
			}
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			ExceptionHandle.handle(e);
		}
	}

3、常量配置信息

package com.cvicse.inforguard.cssp.util;
/**
 * 常量定義
 * 
 * 描述:<p>    功能描述,該部分必須以中文句號結尾。</p>
 * 創建日期:2012-6-27 上午9:57:05<br>
 * @author:tianyj<br> 
 * @update:$Date$<br>
 * @version:$Revision$<br>
 * @since 版本號,用來指定該類是從整個項目的哪個版本開始加入到項目中的
 */
public class Constant {
	// Hibernate配置文件名稱
	public static final String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
	// 配置文件中URL屬性名稱
	public static final String CONNECTION_URL = "hibernate.connection.url";
	// 配置文件中數據庫用戶名
	public static final String CONNECTION_USERNAME = "hibernate.connection.username";
	// 配置文件中數據庫密碼
	public static final String CONNECTION_PASSWORD = "hibernate.connection.password";
	public static final String PROPERTY_XPATH = "/hibernate-configuration/session-factory/property";
	public static final String MAPPING_XPATH = "/hibernate-configuration/session-factory/mapping";
	public static final String ALL_XPATH = "/hibernate-configuration/session-factory";
}

4、Main方法

package com.cvicse.inforguard.cssp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;

import com.cvicse.inforguard.cssp.exception.EXP_Base;
import com.cvicse.inforguard.cssp.service.CitySrv;
import com.cvicse.inforguard.cssp.storage.dao.HibernateSessionFactory;
import com.cvicse.inforguard.cssp.storage.model.TB_City;
import com.cvicse.inforguard.cssp.util.ConfigHibernateHelper;
import com.cvicse.inforguard.cssp.util.Constant;

public class Process {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CitySrv cs = new CitySrv();
		try {
			TB_City city = cs.getCity(85);
			System.out.println(city.getId() + " " + city.getName());
			System.out.println("-------------------------------------------------------------------");
			
			
			// 模仿前臺傳送數據
			Map<String, String> paraMap = new HashMap<String, String>();
			paraMap.put(Constant.CONNECTION_URL, "jdbc:mysql://192.168.62.173:3306/cssp?characterEncoding=UTF-8");
			paraMap.put(Constant.CONNECTION_USERNAME, "root");
			paraMap.put(Constant.CONNECTION_PASSWORD, "root");
			// 修改緩存配置
			HibernateSessionFactory.getConfiguration(paraMap);
			city = cs.getCity(85);
			System.out.println(city.getId() + " " + city.getName());
			// 改變重新XML
			changeDatabase(paraMap);
		} catch (EXP_Base e) {
			e.printStackTrace();
		}
	}

	public static void changeDatabase(Map<String, String> paraMap){
		ConfigHibernateHelper helper = new ConfigHibernateHelper();
		// 讀取配置文件
		List<Element> nodeList = helper.read(
				Constant.CONFIG_FILE_LOCATION, Constant.PROPERTY_XPATH, Constant.MAPPING_XPATH);
		System.out.println();System.out.println();System.out.println();
		// 修改前
		printValue(nodeList);
		System.out.println();System.out.println();System.out.println();
		nodeList = helper.replaceNewValue(paraMap, nodeList);
		helper.write(Constant.CONFIG_FILE_LOCATION, nodeList);
		// 修改後
		printValue(nodeList);
		System.out.println();System.out.println();System.out.println();
	}
	
	public static void printValue(List<Element> nodeList){
		for (Element property : nodeList) {  
            String name = property.attributeValue("name");  
            String text = property.getText();
            if(Constant.CONNECTION_URL.equals(name) 
            		|| Constant.CONNECTION_USERNAME.equals(name) || Constant.CONNECTION_PASSWORD.equals(name)){
            	System.out.println("$$$$$$$$$$$"+name + " : " + text+"$$$$$$$$$$$$$$$");
            }
        }
	}
}

PS:

<1>在不連接網絡的情況下,會報驗證錯誤。
   reader.setEntityResolver(new NoOpEntityResolver());
   NoOpEntityResolver,這個類是實現了EntityResolver接口,不讓reader讀取的時候進行驗證。

package com.cvicse.inforguard.cssp.util;

import java.io.IOException;
import java.io.StringBufferInputStream;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class NoOpEntityResolver implements EntityResolver{

	@SuppressWarnings("deprecation")
    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
	    // TODO Auto-generated method stub
	    return new InputSource(new StringBufferInputStream(""));
    }

}

<2>在jdom、dom4j中使用xpath需要導入jaxen.jar包,這個資源是包含api和jar的zip包

<3>在Hibernater緩存中存在的形式
hibernate.connection.url=jdbc:mysql://192.168.62.173:3306/cssp?characterEncoding=UTF-8
hibernate.connection.password=root
hibernate.connection.username=root

根據key得到緩存中value
在Hibernate配置文件中,配置信息connection.url是可以得到的,在緩存中Hibernate默認加上Hibernate.connection.url
configuration.getProperties().get("connection.url")

在Hibernate硬性的寫成Hibernate.connection.url,上述方式獲取的值爲null,key=Hibernate.connection.url

SessionFactory中key-value詳細信息:

[java.vendor=Sun Microsystems Inc., 
sun.java.launcher=SUN_STANDARD, 
hibernate.connection.url=jdbc:mysql://192.168.62.173:3306/cssp?characterEncoding=UTF-8, 
sun.management.compiler=HotSpot Client Compiler, 
os.name=Windows XP, 
sun.boot.class.path=C:\Program Files\Java\jdk1.6.0_17\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_17\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_17\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.6.0_17\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_17\jre\lib\jce.jar;C:\Program Files\Java\jdk1.6.0_17\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_17\jre\classes, 
sun.desktop=windows,
 hibernate.c3p0.max_size=30, 
java.vm.specification.vendor=Sun Microsystems Inc., 
java.runtime.version=1.6.0_17-b04, 
hibernate.connection.autocommit=true, 
hibernate.c3p0.min_size=5, 
user.name=Administrator, 
connection.driver_class=com.mysql.jdbc.Driver, 
jdbc.fetch_size=50, 
hibernate.c3p0.timeout=25200, 
user.language=zh, 
sun.boot.library.path=C:\Program Files\Java\jdk1.6.0_17\jre\bin, 
hibernate.order_inserts=false, 
hibernate.jdbc.use_scrollable_resultset=true, 
dialect=com.cvicse.inforguard.cssp.storage.dialect.MySqlDialectEx, 
java.version=1.6.0_17, 
user.timezone=, 
jdbc.batch_size=50, 
sun.arch.data.model=32, 
java.endorsed.dirs=C:\Program Files\Java\jdk1.6.0_17\jre\lib\endorsed, 
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86, 
sun.jnu.encoding=GBK, 
file.encoding.pkg=sun.io, 
file.separator=\, 
java.specification.name=Java Platform API Specification, 
hibernate.format_sql=false, 
java.class.version=50.0, 
user.country=CN, 
connection.url=jdbc:mysql://192.168.51.219:13306/cssp?characterEncoding=UTF-8, 
java.home=C:\Program Files\Java\jdk1.6.0_17\jre, java.vm.info=mixed mode, 
hibernate.c3p0.validate=true, os.version=5.1, 
hibernate.jdbc.fetch_size=50, 
path.separator=;, 
connection.password=cvicse, 
java.vm.version=14.3-b01, 
hibernate.connection.password=root, 
user.variant=, 
hibernate.jdbc.batch_size=50, 
java.awt.printerjob=sun.awt.windows.WPrinterJob, 
hibernate.order_updates=false, 
sun.io.unicode.encoding=UnicodeLittle, 
awt.toolkit=sun.awt.windows.WToolkit, 
hibernate.connection.username=root, 
user.home=C:\Documents and Settings\Administrator, 
java.specification.vendor=Sun Microsystems Inc., 
java.library.path=C:\Program Files\Java\jdk1.6.0_17\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.6.0_17\jre\bin;C:\Program Files\Java\jdk1.6.0_17\bin;C:\oracle\ora92\bin;C:\myProgram File\ant-1.7.1\bin;C:\Program Files\Java\jre6\lib;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\TortoiseSVN\bin;C:\decompli;D:\IDE\apache-maven-2.2.1\bin;C:\Program Files\Microsoft Visual Studio\Common\Tools\WinNT;C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin;C:\Program Files\Microsoft Visual Studio\Common\Tools;C:\Program Files\Microsoft Visual Studio\VC98\bin;C:\Program Files\IDM Computer Solutions\UltraEdit-32, java.vendor.url=http://java.sun.com/, hibernate.connection.driver_class=com.mysql.jdbc.Driver, connection.username=root, java.vm.vendor=Sun Microsystems Inc., hibernate.dialect=com.cvicse.inforguard.cssp.storage.dialect.MySqlDialectEx, java.runtime.name=Java(TM) SE Runtime Environment, java.class.path=D:\hibernateTest\bin;D:\hibernateTest\lib\antlr-2.7.7.jar;D:\hibernateTest\lib\asm-all-3.2.jar;D:\hibernateTest\lib\c3p0-0.9.1.jar;D:\hibernateTest\lib\cglib-2.2.jar;D:\hibernateTest\lib\com.springsource.org.apache.commons.collections-3.2.0.jar;D:\hibernateTest\lib\dom4j-1.6.1.jar;D:\hibernateTest\lib\ehcache-1.1.jar;D:\hibernateTest\lib\hibernate-3.6.0.jar;D:\hibernateTest\lib\hibernate-jpa-2.0-api-1.0.0.Final.jar;D:\hibernateTest\lib\javassist-3.12.0.GA.jar;D:\hibernateTest\lib\jta-1.1.jar;D:\hibernateTest\lib\mysql-connector-java-5.1.11.jar;D:\hibernateTest\lib\loong-logging-api-1.2.4.jar;D:\hibernateTest\lib\loong-logging-impl-1.2.4.qualifier.jar;D:\IDE\Repository\org\dom4j\com.springsource.org.dom4j\1.6.1\com.springsource.org.dom4j-1.6.1.jar;D:\IDE\Repository\jaxen\jaxen\1.1.1\jaxen-1.1.1.jar, 
hibernate.bytecode.use_reflection_optimizer=false, 
java.vm.specification.name=Java Virtual Machine Specification, 
java.vm.specification.version=1.0, 
sun.cpu.endian=little, 
sun.os.patch.level=Service Pack 3, 
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider, 
connection.autocommit=true, connection.pool_size=8, 
java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\, 
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi, 
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, 
os.arch=x86, 
java.ext.dirs=C:\Program Files\Java\jdk1.6.0_17\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext, 
user.dir=D:\hibernateTest, hibernate.use_sql_comments=false, 
hibernate.c3p0.idle_test_period=3000, 
line.separator=, 
java.vm.name=Java HotSpot(TM) Client VM, 
hibernate.c3p0.acquire_increment=2, 
file.encoding=UTF-8, 
java.specification.version=1.6, 
hibernate.connection.pool_size=8, 
hibernate.show_sql=false, 
hibernate.c3p0.max_statements=100]





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章