Hibernate根据方言dialect动态连接多数据库
由于最近需要在web项目中动态链接不同地址的数据库,且要链接的子数据库的信息在总数据库(即web项目的主数据库)的表中,所以动手写了一个类。
web项目试用了hibernate,动态生成的子数据库链接打算也用hibernate,虽然动态生成的sessionfactory类,以及Configuration配置没有子数据库的对象关系映射,但是使用 native SQL 也方便。
请看后来写的改进篇,有什么建议请留言------------
Hibernate动态连接多数据库改进篇
-------------------------------------------------------
代码如下:
public class TempSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
//private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private Configuration configuration = new Configuration();
private org.hibernate.SessionFactory sessionFactory;
//private static String configFile = CONFIG_FILE_LOCATION;
/* static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}*/
public void setConfiguration(String dialect, String driverClass,
String ipAddress, String port, String dataBaseName,
String username, String password) {
String connection_url = "";
Configuration configuration = new Configuration();
if (dialect.indexOf("MySQL") > -1) {
System.out.println("%%%% DataBase type is MySql %%%%");
connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
} else if (dialect.indexOf("SQLServer") > -1) {
System.out.println("%%%% DataBase type is SQLServer %%%%");
connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
+ ";DataBaseName=" + dataBaseName;
} else if (dialect.indexOf("Oracle") > -1) {
System.out.println("%%%% DataBase type is Oracle %%%%");
connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
+ ":" + dataBaseName;
// configuration.setProperty("hibernate.connection.oracle.jdbc.V8Compatible","true");
}
configuration.setProperty("hibernate.dialect", dialect);
configuration.setProperty("hibernate.connection.url", connection_url);
configuration.setProperty("hibernate.connection.driver_class",
driverClass);
configuration.setProperty("hibernate.connection.username", username);
configuration.setProperty("hibernate.connection.password", password);
// configuration.setProperty("hibernate.default_schema", "dbo");
// configuration.setProperty("hibernate.default_catalog", dataBaseName);
// configuration.setProperty("hibernate.show_sql", "true");
this.configuration = configuration;
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*
*/
public Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public void rebuildSessionFactory() {
try {
//configuration.configure(configFile);
sessionFactory = this.configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
/* public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}*/
/**
* return hibernate configuration
*
*/
public Configuration getConfiguration() {
return configuration;
}
}
测试类代码:
在 databasename1 库中建 testtable表,字段id,name2个
在 databasename2 库中建 testtable2表,字段id,name2个
public class TestCase1 {
public static void main(String[] args) {
try{
Configuration configuration1 = new Configuration();
TempSessionFactory tempSessionFactory1 = new TempSessionFactory(configuration1);
tempSessionFactory1.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
"jdbc:sqlserver://*1.*1.*1.*1","1433","databasename1","sa","sa");
Session session1=tempSessionFactory1.getSession();
Transaction tx1 = session1.beginTransaction();
Query query1 = session1.createSQLQuery("select name as aaa from testtable ").setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();
System.out.println("fd1111===="+obj1.get("aaa"));
Configuration configuration2 = new Configuration();
TempSessionFactory tempSessionFactory2 = new TempSessionFactory(configuration2);
tempSessionFactory2.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
"jdbc:sqlserver://*2.*2.*2.*2","1433","databasename2","sa","sa");
Session session2=tempSessionFactory2.getSession();
Transaction tx2 = session2.beginTransaction();
Query query2 = session2.createSQLQuery("select name as aaa from testtable2 ").setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();
System.out.println("fd2222===="+obj2.get("aaa"));
}catch (Exception e) {
System.err.println(e);
// TODO: handle exception
}
}
}
请看后来写的改进篇--------------------
Hibernate动态连接多数据库改进篇
------------------------------------------
分享到:
相关推荐
达梦数据库各版本的hibernate方言包,包含版本 DmDialect-for-hibernate2.0、DmDialect-for-hibernate2.1、DmDialect-for-hibernate3.0、DmDialect-for-hibernate3.1、DmDialect-for-hibernate3.6、DmDialect-for-...
达梦数据库方言 (dialect) jar包 包含hibernate各版本,DmHibernateSpatial-1.0.jar, DmHibernateSpatial-1.1.jar,DmDialect-for-hibernate5.3.jar ... DmDictionary.jar,dmjooq-dialect-3.12.3.jar,gt-dameng-...
Hibernate连接SQLite配置步骤: 1、添加SQLite库: 1.1、将两个jar包:com.zy.hibernate.dialect.SQLiteDialect.jar、sqlite-jdbc-3.7.2.jar拷贝到“\WEB-INF\lib”文件夹下; 2、配置hibernate: 2.1、将...
* 达梦8 hibernate方言包对应版本说明 /*************************************** jar包在dialect目录下: 1. DmDialect-for-hibernate2.0.jar 对应 Jdk1.4及以上, hibernate2.0 环境 2. DmDialect-for-hibernate2.1...
瀚高数据库hibernate方言 hgdb-hibernate-dialect
达梦8数据库jdbc依赖包 1. DmJdbcDriver16 对应 Jdk1.6 及以上环境 2. DmJdbcDriver17 对应 Jdk1.7 及以上环境 3. DmJdbcDriver18 对应 Jdk1.8 及以上环境 ---------- maven仓库下载 group id: com.dameng 各版本jar...
达梦Hibernate方言2.0至4.0,当工具书用的.最新方言还是要参考用户手册.方言覆盖的数据库越来越多了
Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect Sybase org.hibernate.dialect.SybaseDialect Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect Microsoft SQL Server org.hibernate....
国产达梦dialect方言jar包,本文亲自整理,没有坑
达梦数据库7.6最新的驱动包及hibernate方言包,含JDK1.5到JDK1.8驱动包和haibernate 5.3及一下方言包
集成Hibernate的方言,版本有oscarHibernate36.jar,oscarHibernate4.jar,oscarHibernate5.jar
连接达梦数据所必须的驱动和方言 达梦7JDBC驱动分为Dm7JdbcDriver15、Dm7JdbcDriver16、Dm7Jdbc...达梦7提供不同hibernate和jdk版本的方言包,用户可根据开发环境选择对应的方言包版本,相关方言包驱动在dialect目录下;
hibernate中访问access数据库需要的jar包hibernate2access
3.8. Hibernate SQL方言 (hibernate.dialect) 3.9. Hibernate日志类别 3.10. JTA TransactionManagers 9.1. 继承映射特性(Features of inheritance mappings) 16.1. 别名注射(alias injection names) 19.1. ...
此文件中包了SpringBoot集成达梦7中所需要的驱动及方言jar包
hibernate.dialect = org.hibernate.dialect.MySQLDialect //指定数据库使用的sql方言(oracle、mysql) hibernate.connection.driver_class=com.mysql.jdbc.Driver //指定数据库的驱动程序 hibernate.connection....
—为true表示将Hibernate发送给数据库的sql显示出来 –> ”show_sql”>true <!– SQL方言,这边设定的是MySQL –> ”dialect”>net.sf.hibernate.dialect.MySQLDialect</property> <!– 一次读的数据库记录数 –...
之前做瀚高数据库迁移时,搜集到的瀚高数据库相关的一切资源
首先,为Cloud Spanner Hibernate方言和Cloud Spanner JDBC驱动程序添加Maven依赖项。 方言的Maven坐标: < groupId>com.google.cloud</ groupId> < artifactId>google-cloud-spanner-hibernate-dialect...