您的位置:首页 > 编程语言 > Java开发

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

2012-06-27 17:13 477 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: