Java工程中动态改变Hibernate的数据库连接信息总结

1、XML解析帮助类,采用Dom4j工具类进行处理

  1. package com.cvicse.inforguard.cssp.util;

  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.UnsupportedEncodingException;
  7. import java.util.List;
  8. import java.util.Map;

  9. import org.dom4j.Document;
  10. import org.dom4j.DocumentException;
  11. import org.dom4j.DocumentHelper;
  12. import org.dom4j.Element;
  13. import org.dom4j.io.OutputFormat;
  14. import org.dom4j.io.SAXReader;
  15. import org.dom4j.io.XMLWriter;
  16. import org.dom4j.xpath.DefaultXPath;


  17. /**
  18. *
  19. *
  20. * 描述:<p> 读取、重写Hibernate配置文件的工具类。</p>
  21. * 创建日期:2012-6-27 上午9:59:49<br>
  22. * @author:tianyj<br>
  23. * @update:$Date$<br>
  24. * @version:$Revision$<br>
  25. * @since 版本号,用来指定该类是从整个项目的哪个版本开始加入到项目中的
  26. */
  27. public class ConfigHibernateHelper {

  28. private SAXReader reader = null;
  29. private File file = null;
  30. private String url = null;
  31. private Document document = null;
  32. private List<Element> nodeList = null;

  33. private XMLWriter writer = null;


  34. /**
  35. * 读取XML文件,返回根据过滤条件进行过滤的节点列表
  36. * @param fileName 文件名称
  37. * @param xpath 过滤条件
  38. * @return 节点元素列表
  39. */
  40. public List<Element> read(String fileName, String pro_xpath, String map_xpath){
  41. reader = new SAXReader();
  42. try {
  43. url = this.getFilePath(fileName);
  44. file = new File(url);
  45. reader.setEntityResolver(new NoOpEntityResolver());
  46. document = reader.read(file);
  47. // 获得hibernate-configuration:session-factory下的property属性节点列表
  48. DefaultXPath propertyPath = new DefaultXPath(pro_xpath);
  49. nodeList = getNodeList(document, propertyPath);
  50. // 获得hibernate-configuration:session-factory下的mapping属性节点列表
  51. DefaultXPath mappingPath = new DefaultXPath(map_xpath);
  52. List<Element> mappings = getNodeList(document, mappingPath);

  53. nodeList.addAll(mappings);

  54. } catch (DocumentException e) {
  55. e.printStackTrace();
  56. }
  57. return nodeList;
  58. }

  59. /**
  60. * 根据条件返回节点列表
  61. * @param document 文档变量
  62. * @param propertyPath 过滤条件对象
  63. * @return
  64. */
  65. @SuppressWarnings("unchecked")
  66. private List<Element> getNodeList(Document document, DefaultXPath propertyPath) {
  67. return propertyPath.selectNodes(document);
  68. }

  69. /**
  70. * 返回配置文件的路径
  71. * @param fileName
  72. * @return
  73. */
  74. private String getFilePath(String fileName){
  75. return getClass().getClassLoader().getResource(fileName).getPath();
  76. }

  77. /**
  78. * 替换从前台传递的配置新的数据库连接属性
  79. * @param paraMap 修改的数据key-value
  80. * @param nodeList 节点列表
  81. */
  82. public List<Element> replaceNewValue(Map<String,String> paraMap, List<Element> nodeList){
  83. // 循环需要修改的节点信息,从前台进行传递过来
  84. for(Map.Entry<String, String> entry : paraMap.entrySet()){
  85. for (Element property : nodeList) {
  86. String name = property.attributeValue("name");
  87. // 过滤掉Mapping配置文件节点
  88. String resource = property.attributeValue("resource");
  89. if(null != resource && "resource".equals(resource)){
  90. break;
  91. }
  92. // 设置修改后的属性值
  93. if(entry.getKey().equals(name)
  94. || entry.getKey().equals(name) || entry.getKey().equals(name)){
  95. property.setText(entry.getValue());
  96. }
  97. }
  98. }
  99. return nodeList;
  100. }

  101. /**
  102. * 把配置信息从新写入
  103. * @param nodeList
  104. * @param fileName
  105. * @return
  106. */
  107. public boolean write(String fileName, List<Element> nodeList){
  108. url = this.getFilePath(fileName);
  109. // document
  110. Document document = DocumentHelper.createDocument();
  111. // 设置DocType
  112. document.addDocType("hibernate-configuration" ,
  113. "-//Hibernate/Hibernate Configuration DTD 3.0//EN" ,
  114. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
  115. // hibernate-configuration
  116. Element configuration = document.addElement("hibernate-configuration");
  117. // session-factory
  118. Element sessionfactory = configuration.addElement("session-factory");
  119. sessionfactory.addComment("Database connection settings");
  120. // 添加属性
  121. for(Element property : nodeList){
  122. String name = property.attributeValue("name");
  123. String resource = property.attributeValue("resource");
  124. String text = property.getText();
  125. // property节点操作方式
  126. if(null != name && null!=text && !"".equals(name) && !"".equals(text)){
  127. Element proElement = sessionfactory.addElement("property");
  128. proElement.addAttribute("name", property.attributeValue("name").trim());
  129. proElement.setText(property.getText().trim());
  130. }else if(null != resource && !"".equals(resource)){
  131. // mapping节点操作方式
  132. Element mapping = sessionfactory.addElement("mapping");
  133. mapping.addAttribute("resource", property.attributeValue("resource").trim());
  134. }

  135. }

  136. //设置输出格式
  137. OutputFormat format = new OutputFormat();
  138. format.setEncoding("utf-8");
  139. format.setIndent(true);
  140. format.setLineSeparator("\n");
  141. format.setNewlines(true);

  142. try {
  143. writer = new XMLWriter(format);
  144. writer.setOutputStream(new FileOutputStream(url));
  145. writer.write(document);
  146. writer.flush();
  147. } catch (UnsupportedEncodingException e) {
  148. e.printStackTrace();
  149. } catch (FileNotFoundException e) {
  150. e.printStackTrace();
  151. } catch (IOException e) {
  152. e.printStackTrace();
  153. } finally {
  154. if(writer != null) {
  155. try {
  156. writer.close();
  157. } catch (IOException e) {
  158. e.printStackTrace();
  159. }
  160. }
  161. }
  162. return true;
  163. }
  164. }

2、修改缓存中Configuration配置数据库的信息

  1. /**
  2. * 根据前台传递的数据库配置信息进行立即修改
  3. * @param paraMap
  4. * @throws EXP_Base
  5. */
  6. public static void getConfiguration(Map<String, String> paraMap) throws EXP_Base{
  7. try {
  8. // 在Hibernate的缓存中移除数据库URL、用户名、密码配置信息
  9. configuration.getProperties().remove(Constant.CONNECTION_URL);
  10. configuration.getProperties().remove(Constant.CONNECTION_USERNAME);
  11. configuration.getProperties().remove(Constant.CONNECTION_PASSWORD);
  12. // 在Hibernate的缓存中添加新的数据库URL、用户名、密码配置信息
  13. configuration.getProperties().setProperty(
  14. Constant.CONNECTION_URL, paraMap.get(Constant.CONNECTION_URL));
  15. configuration.getProperties().setProperty(
  16. Constant.CONNECTION_USERNAME, paraMap.get(Constant.CONNECTION_USERNAME));
  17. configuration.getProperties().setProperty(
  18. Constant.CONNECTION_PASSWORD, paraMap.get(Constant.CONNECTION_PASSWORD));
  19. /*
  20. * 销毁SessionFactory并释放所有资源(缓存,连接池等)。
  21. */
  22. if (sessionFactory != null) {
  23. sessionFactory.close();
  24. }
  25. sessionFactory = configuration.buildSessionFactory();
  26. } catch (Exception e) {
  27. ExceptionHandle.handle(e);
  28. }
  29. }

3、常量配置信息
  1. package com.cvicse.inforguard.cssp.util;
  2. /**
  3. * 常量定义
  4. *
  5. * 描述:<p> 功能描述,该部分必须以中文句号结尾。</p>
  6. * 创建日期:2012-6-27 上午9:57:05<br>
  7. * @author:tianyj<br>
  8. * @update:$Date$<br>
  9. * @version:$Revision$<br>
  10. * @since 版本号,用来指定该类是从整个项目的哪个版本开始加入到项目中的
  11. */
  12. public class Constant {
  13. // Hibernate配置文件名称
  14. public static final String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
  15. // 配置文件中URL属性名称
  16. public static final String CONNECTION_URL = "hibernate.connection.url";
  17. // 配置文件中数据库用户名
  18. public static final String CONNECTION_USERNAME = "hibernate.connection.username";
  19. // 配置文件中数据库密码
  20. public static final String CONNECTION_PASSWORD = "hibernate.connection.password";
  21. public static final String PROPERTY_XPATH = "/hibernate-configuration/session-factory/property";
  22. public static final String MAPPING_XPATH = "/hibernate-configuration/session-factory/mapping";
  23. public static final String ALL_XPATH = "/hibernate-configuration/session-factory";
  24. }

4、Main方法
  1. package com.cvicse.inforguard.cssp;

  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;

  5. import org.dom4j.Element;

  6. import com.cvicse.inforguard.cssp.exception.EXP_Base;
  7. import com.cvicse.inforguard.cssp.service.CitySrv;
  8. import com.cvicse.inforguard.cssp.storage.dao.HibernateSessionFactory;
  9. import com.cvicse.inforguard.cssp.storage.model.TB_City;
  10. import com.cvicse.inforguard.cssp.util.ConfigHibernateHelper;
  11. import com.cvicse.inforguard.cssp.util.Constant;

  12. public class Process {

  13. /**
  14. * @param args
  15. */
  16. public static void main(String[] args) {
  17. CitySrv cs = new CitySrv();
  18. try {
  19. TB_City city = cs.getCity(85);
  20. System.out.println(city.getId() + " " + city.getName());
  21. System.out.println("-------------------------------------------------------------------");


  22. // 模仿前台传送数据
  23. Map<String, String> paraMap = new HashMap<String, String>();
  24. paraMap.put(Constant.CONNECTION_URL, "jdbc:mysql://192.168.62.173:3306/cssp?characterEncoding=UTF-8");
  25. paraMap.put(Constant.CONNECTION_USERNAME, "root");
  26. paraMap.put(Constant.CONNECTION_PASSWORD, "root");
  27. // 修改缓存配置
  28. HibernateSessionFactory.getConfiguration(paraMap);
  29. city = cs.getCity(85);
  30. System.out.println(city.getId() + " " + city.getName());
  31. // 改变重新XML
  32. changeDatabase(paraMap);
  33. } catch (EXP_Base e) {
  34. e.printStackTrace();
  35. }
  36. }

  37. public static void changeDatabase(Map<String, String> paraMap){
  38. ConfigHibernateHelper helper = new ConfigHibernateHelper();
  39. // 读取配置文件
  40. List<Element> nodeList = helper.read(
  41. Constant.CONFIG_FILE_LOCATION, Constant.PROPERTY_XPATH, Constant.MAPPING_XPATH);
  42. System.out.println();System.out.println();System.out.println();
  43. // 修改前
  44. printValue(nodeList);
  45. System.out.println();System.out.println();System.out.println();
  46. nodeList = helper.replaceNewValue(paraMap, nodeList);
  47. helper.write(Constant.CONFIG_FILE_LOCATION, nodeList);
  48. // 修改后
  49. printValue(nodeList);
  50. System.out.println();System.out.println();System.out.println();
  51. }

  52. public static void printValue(List<Element> nodeList){
  53. for (Element property : nodeList) {
  54. String name = property.attributeValue("name");
  55. String text = property.getText();
  56. if(Constant.CONNECTION_URL.equals(name)
  57. || Constant.CONNECTION_USERNAME.equals(name) || Constant.CONNECTION_PASSWORD.equals(name)){
  58. System.out.println("$$$$$$$$$$$"+name + " : " + text+"$$$$$$$$$$$$$$$");
  59. }
  60. }
  61. }
  62. }

PS:

<1>在不连接网络的情况下,会报验证错误。
reader.setEntityResolver(new NoOpEntityResolver());
NoOpEntityResolver,这个类是实现了EntityResolver接口,不让reader读取的时候进行验证。

  1. package com.cvicse.inforguard.cssp.util;

  2. import java.io.IOException;
  3. import java.io.StringBufferInputStream;

  4. import org.xml.sax.EntityResolver;
  5. import org.xml.sax.InputSource;
  6. import org.xml.sax.SAXException;

  7. public class NoOpEntityResolver implements EntityResolver{

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

  14. }

< 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详细信息:

  1. [java.vendor=Sun Microsystems Inc.,
  2. sun.java.launcher=SUN_STANDARD,
  3. hibernate.connection.url=jdbc:mysql://192.168.62.173:3306/cssp?characterEncoding=UTF-8,
  4. sun.management.compiler=HotSpot Client Compiler,
  5. os.name=Windows XP,
  6. 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,
  7. sun.desktop=windows,
  8. hibernate.c3p0.max_size=30,
  9. java.vm.specification.vendor=Sun Microsystems Inc.,
  10. java.runtime.version=1.6.0_17-b04,
  11. hibernate.connection.autocommit=true,
  12. hibernate.c3p0.min_size=5,
  13. user.name=Administrator,
  14. connection.driver_class=com.mysql.jdbc.Driver,
  15. jdbc.fetch_size=50,
  16. hibernate.c3p0.timeout=25200,
  17. user.language=zh,
  18. sun.boot.library.path=C:\Program Files\Java\jdk1.6.0_17\jre\bin,
  19. hibernate.order_inserts=false,
  20. hibernate.jdbc.use_scrollable_resultset=true,
  21. dialect=com.cvicse.inforguard.cssp.storage.dialect.MySqlDialectEx,
  22. java.version=1.6.0_17,
  23. user.timezone=,
  24. jdbc.batch_size=50,
  25. sun.arch.data.model=32,
  26. java.endorsed.dirs=C:\Program Files\Java\jdk1.6.0_17\jre\lib\endorsed,
  27. sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86,
  28. sun.jnu.encoding=GBK,
  29. file.encoding.pkg=sun.io,
  30. file.separator=\,
  31. java.specification.name=Java Platform API Specification,
  32. hibernate.format_sql=false,
  33. java.class.version=50.0,
  34. user.country=CN,
  35. connection.url=jdbc:mysql://192.168.51.219:13306/cssp?characterEncoding=UTF-8,
  36. java.home=C:\Program Files\Java\jdk1.6.0_17\jre, java.vm.info=mixed mode,
  37. hibernate.c3p0.validate=true, os.version=5.1,
  38. hibernate.jdbc.fetch_size=50,
  39. path.separator=;,
  40. connection.password=cvicse,
  41. java.vm.version=14.3-b01,
  42. hibernate.connection.password=root,
  43. user.variant=,
  44. hibernate.jdbc.batch_size=50,
  45. java.awt.printerjob=sun.awt.windows.WPrinterJob,
  46. hibernate.order_updates=false,
  47. sun.io.unicode.encoding=UnicodeLittle,
  48. awt.toolkit=sun.awt.windows.WToolkit,
  49. hibernate.connection.username=root,
  50. user.home=C:\Documents and Settings\Administrator,
  51. java.specification.vendor=Sun Microsystems Inc.,
  52. 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,
  53. hibernate.bytecode.use_reflection_optimizer=false,
  54. java.vm.specification.name=Java Virtual Machine Specification,
  55. java.vm.specification.version=1.0,
  56. sun.cpu.endian=little,
  57. sun.os.patch.level=Service Pack 3,
  58. hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider,
  59. connection.autocommit=true, connection.pool_size=8,
  60. java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\,
  61. java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi,
  62. java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment,
  63. os.arch=x86,
  64. java.ext.dirs=C:\Program Files\Java\jdk1.6.0_17\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext,
  65. user.dir=D:\hibernateTest, hibernate.use_sql_comments=false,
  66. hibernate.c3p0.idle_test_period=3000,
  67. line.separator=,
  68. java.vm.name=Java HotSpot(TM) Client VM,
  69. hibernate.c3p0.acquire_increment=2,
  70. file.encoding=UTF-8,
  71. java.specification.version=1.6,
  72. hibernate.connection.pool_size=8,
  73. hibernate.show_sql=false,
  74. hibernate.c3p0.max_statements=100]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值