Hibernate根据方言dialect动态连接多数据库
Hibernate根据方言dialect动态连接多数据库
由于最近需要在web项目中动态链接不同地址的数据库,且要链接的子数据库的信息在总数据库(即web项目的主数据库)的表中,所以动手写了一个类。
web项目试用了hibernate,动态生成的子数据库链接打算也用hibernate,虽然动态生成的sessionfactory类,以及Configuration配置没有子数据库的对象关系映射,但是使用 native SQL 也方便。
代码如下:
- 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根据方言dialect动态连接多数据库的更多相关文章
- Jpa 重写方言dialect 使用oracle / mysql 数据库自定义函数
在使用criteria api进行查询时 criteriaBuilder只提供了一个部分标准的sql函数,但当我们需要使用oracle特有的行转列函数wm_concat或 mysql特有的行转列函数g ...
- Grails连接外部数据库注意事项Could not determine Hibernate dialect for database name [Oracle]!
初次使用Grails时,使用其内置数据库,一直不会出错,但迁移到外部数据库时会出错Could not determine Hibernate dialect for database name [Or ...
- Hibernate SQL方言 (hibernate.dialect) Spring配置文件applicationContext.xml
转自:http://www.cnblogs.com/wj-wangjun/archive/2009/10/21/1587624.html Hibernate SQL方言 (hibernate.dial ...
- 连接Oracle数据库的Hibernate配置文件
连接Oracle数据库的Hibernate配置文件连接Oracle的Hibernate配置文件有两种格式,一种是xml格式的,另一种是Java属性文件格式的.下面分别给出这两种格式配置文件的代码. 1 ...
- atitit.动态加载数据库配置in orm hibernate mybatis
atitit.动态加载数据库配置in orm 1. 动态加载数据库配置的优点::: 1 1.1. 组合多个配置文件... 1 1.2. 连接多个数据库 1 2. 基本的流程:::getCfg内存对象, ...
- 在配置hibernate.cfg.xml时需指定使用数据库的方言:
在配置hibernate.cfg.xml时需指定使用数据库的方言: 例: <property name="dialect">org.hibernate.dialect. ...
- idea中创建web项目搭建Hibernate框架连接oracle数据库
hibernate框架 hibernate是数据化持久工具,也是一个开源代码的ORM解决方案.hibernate内部封装了通过jdbc访问数据库的操作,向商场应用提供面向对象的数据访问api. hib ...
- 连接Oracle数据库的Hibernate配置…
连接Oracle数据库的Hibernate配置文件 连接Oracle的Hibernate配置文件有两种格式,一种是xml格式的,另一种是Java属性文件格式的.下面分别给出这两种格式配置文件的代码. ...
- hibernate简单连接mysql数据库配置
使用hibernate连接mysql数据库 1:项目搭建好之后,在lib包中添加必要的jar包,和mysql数据库驱动jar包: jar包可以在hibernate的下载包(hibernate3.3.2 ...
随机推荐
- jquery 报错 Uncaught TypeError: Illegal invocation
遇到这个错误 请检查你的ajax提交方法的参数 1 参数是否都有定义 2 参数个数是否一致 3参数是否都有值(******)
- 3D Math Keynote
[3DMathKeynote] 1.常用公式. 1)(A*B)^T = B^T*A^T. 2)(A*B)^-1 = B^-1*A^-1. 3)|A*B| = |A|*|B|. 4)|M^T|=|M ...
- 141. Linked List Cycle (List; Two-Pointers)
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...
- porwedesigner 去掉引号
PowerDesigner生成的ORACLE 建表脚本中去掉对象的双引号,设置大.小写 若要将 CDM 中将 Entity的标识符都设为指定的大小写,则可以这么设定: 打开cdm的情况下,进入Tool ...
- CentOS搭建VSFTP服务器
一.安装vsftpd 1.查看是否已经安装vsftpd 2.如果没有,就安装 3.测试是否安装成功 4.安装成功设置开机启动 二.配置vsftpd 1.修改配置文件/etc/vsftpd/vsftpd ...
- python 全栈基础作业题
1.执行 Python 脚本的两种方式 1..直接使用PyCharm执行 2.python run.py 调用python 解释器来调用python脚本 2.简述位.字节的关系 数据存储是以“字节”( ...
- code1154 能量项链
d[l][i]表示:从第i个珠子开始,连续l个珠子合并后释放的最大能量 状态转移方程d[l][i] = d[j][i] + d[l-j][i+j] + w[i]*w[i+j]*w[i+l],j从1到l ...
- Linux 上安装 rlwrap
1.安装rlwrap的初衷; 2.安装rlwrap工具和遇到的问题; 3.使用rlwrap 工具; 1.安装rlwrap的初衷: 在Windows 下使用SQLPLUS都是可以使用上下左右方向键前后左 ...
- es学习-java操作 2.4.0版本
package esjava; import org.elasticsearch.action.bulk.*;import org.elasticsearch.action.delete.Delete ...
- ConfigureAwait(false)避免上下文延续
之前MVC利用MvcHtmlString封装通用下拉菜单,菜单数据需要从webapi获取,自然用到了 await Http Client.GetAsync(Url)方法,前端 @Html.Select ...