Hibernate根据方言dialect动态连接多数据库

由于最近需要在web项目中动态链接不同地址的数据库,且要链接的子数据库的信息在总数据库(即web项目的主数据库)的表中,所以动手写了一个类。

web项目试用了hibernate,动态生成的子数据库链接打算也用hibernate,虽然动态生成的sessionfactory类,以及Configuration配置没有子数据库的对象关系映射,但是使用 native SQL 也方便。

代码如下:

  1. public class TempSessionFactory {
  2. /**
  3. * Location of hibernate.cfg.xml file.
  4. * Location should be on the classpath as Hibernate uses
  5. * #resourceAsStream style lookup for its configuration file.
  6. * The default classpath location of the hibernate config file is
  7. * in the default package. Use #setConfigFile() to update
  8. * the location of the configuration file for the current session.
  9. */
  10. //private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  11. private final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  12. private Configuration configuration = new Configuration();
  13. private org.hibernate.SessionFactory sessionFactory;
  14. //private static String configFile = CONFIG_FILE_LOCATION;
  15. /*  static {
  16. try {
  17. configuration.configure(configFile);
  18. sessionFactory = configuration.buildSessionFactory();
  19. } catch (Exception e) {
  20. System.err
  21. .println("%%%% Error Creating SessionFactory %%%%");
  22. e.printStackTrace();
  23. }
  24. }*/
  25. public void setConfiguration(String dialect, String driverClass,
  26. String ipAddress, String port, String dataBaseName,
  27. String username, String password) {
  28. String connection_url = "";
  29. Configuration configuration = new Configuration();
  30. if (dialect.indexOf("MySQL") > -1) {
  31. System.out.println("%%%% DataBase type is MySql %%%%");
  32. connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
  33. } else if (dialect.indexOf("SQLServer") > -1) {
  34. System.out.println("%%%% DataBase type is SQLServer %%%%");
  35. connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
  36. + ";DataBaseName=" + dataBaseName;
  37. } else if (dialect.indexOf("Oracle") > -1) {
  38. System.out.println("%%%% DataBase type is Oracle %%%%");
  39. connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
  40. + ":" + dataBaseName;
  41. // configuration.setProperty("hibernate.connection.oracle.jdbc.V8Compatible","true");
  42. }
  43. configuration.setProperty("hibernate.dialect", dialect);
  44. configuration.setProperty("hibernate.connection.url", connection_url);
  45. configuration.setProperty("hibernate.connection.driver_class",
  46. driverClass);
  47. configuration.setProperty("hibernate.connection.username", username);
  48. configuration.setProperty("hibernate.connection.password", password);
  49. // configuration.setProperty("hibernate.default_schema", "dbo");
  50. // configuration.setProperty("hibernate.default_catalog", dataBaseName);
  51. // configuration.setProperty("hibernate.show_sql", "true");
  52. this.configuration = configuration;
  53. }
  54. /**
  55. * Returns the ThreadLocal Session instance.  Lazy initialize
  56. * the <code>SessionFactory</code> if needed.
  57. *
  58. *  @return Session
  59. *  @throws HibernateException
  60. *
  61. */
  62. public Session getSession() throws HibernateException {
  63. Session session = (Session) threadLocal.get();
  64. if (session == null || !session.isOpen()) {
  65. if (sessionFactory == null) {
  66. rebuildSessionFactory();
  67. }
  68. session = (sessionFactory != null) ? sessionFactory.openSession()
  69. : null;
  70. threadLocal.set(session);
  71. }
  72. return session;
  73. }
  74. /**
  75. *  Rebuild hibernate session factory
  76. *
  77. */
  78. public void rebuildSessionFactory() {
  79. try {
  80. //configuration.configure(configFile);
  81. sessionFactory = this.configuration.buildSessionFactory();
  82. } catch (Exception e) {
  83. System.err
  84. .println("%%%% Error Creating SessionFactory %%%%");
  85. e.printStackTrace();
  86. }
  87. }
  88. /**
  89. *  Close the single hibernate session instance.
  90. *
  91. *  @throws HibernateException
  92. */
  93. public void closeSession() throws HibernateException {
  94. Session session = (Session) threadLocal.get();
  95. threadLocal.set(null);
  96. if (session != null) {
  97. session.close();
  98. }
  99. }
  100. /**
  101. *  return session factory
  102. *
  103. */
  104. public org.hibernate.SessionFactory getSessionFactory() {
  105. return sessionFactory;
  106. }
  107. /**
  108. *  return session factory
  109. *
  110. *  session factory will be rebuilded in the next call
  111. */
  112. /*  public static void setConfigFile(String configFile) {
  113. HibernateSessionFactory.configFile = configFile;
  114. sessionFactory = null;
  115. }*/
  116. /**
  117. *  return hibernate configuration
  118. *
  119. */
  120. public Configuration getConfiguration() {
  121. return configuration;
  122. }
  123. }

测试类代码: 
在 databasename1 库中建 testtable表,字段id,name2个 
在 databasename2 库中建 testtable2表,字段id,name2个

    1. public class TestCase1 {
    2. public static void main(String[] args) {
    3. try{
    4. Configuration configuration1 = new Configuration();
    5. TempSessionFactory tempSessionFactory1 = new TempSessionFactory(configuration1);
    6. tempSessionFactory1.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
    7. "jdbc:sqlserver://*1.*1.*1.*1","1433","databasename1","sa","sa");
    8. Session session1=tempSessionFactory1.getSession();
    9. Transaction tx1 = session1.beginTransaction();
    10. Query query1 = session1.createSQLQuery("select  name as  aaa  from testtable ").setResultTransformer(
    11. Transformers.ALIAS_TO_ENTITY_MAP);
    12. Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();
    13. System.out.println("fd1111===="+obj1.get("aaa"));
    14. Configuration configuration2 = new Configuration();
    15. TempSessionFactory tempSessionFactory2 = new TempSessionFactory(configuration2);
    16. tempSessionFactory2.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
    17. "jdbc:sqlserver://*2.*2.*2.*2","1433","databasename2","sa","sa");
    18. Session session2=tempSessionFactory2.getSession();
    19. Transaction tx2 = session2.beginTransaction();
    20. Query query2 = session2.createSQLQuery("select  name as  aaa  from testtable2 ").setResultTransformer(
    21. Transformers.ALIAS_TO_ENTITY_MAP);
    22. Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();
    23. System.out.println("fd2222===="+obj2.get("aaa"));
    24. }catch (Exception e) {
    25. System.err.println(e);
    26. // TODO: handle exception
    27. }
    28. }
    29. }

Hibernate根据方言dialect动态连接多数据库的更多相关文章

  1. Jpa 重写方言dialect 使用oracle / mysql 数据库自定义函数

    在使用criteria api进行查询时 criteriaBuilder只提供了一个部分标准的sql函数,但当我们需要使用oracle特有的行转列函数wm_concat或 mysql特有的行转列函数g ...

  2. Grails连接外部数据库注意事项Could not determine Hibernate dialect for database name [Oracle]!

    初次使用Grails时,使用其内置数据库,一直不会出错,但迁移到外部数据库时会出错Could not determine Hibernate dialect for database name [Or ...

  3. Hibernate SQL方言 (hibernate.dialect) Spring配置文件applicationContext.xml

    转自:http://www.cnblogs.com/wj-wangjun/archive/2009/10/21/1587624.html Hibernate SQL方言 (hibernate.dial ...

  4. 连接Oracle数据库的Hibernate配置文件

    连接Oracle数据库的Hibernate配置文件连接Oracle的Hibernate配置文件有两种格式,一种是xml格式的,另一种是Java属性文件格式的.下面分别给出这两种格式配置文件的代码. 1 ...

  5. atitit.动态加载数据库配置in orm hibernate mybatis

    atitit.动态加载数据库配置in orm 1. 动态加载数据库配置的优点::: 1 1.1. 组合多个配置文件... 1 1.2. 连接多个数据库 1 2. 基本的流程:::getCfg内存对象, ...

  6. 在配置hibernate.cfg.xml时需指定使用数据库的方言:

    在配置hibernate.cfg.xml时需指定使用数据库的方言: 例: <property name="dialect">org.hibernate.dialect. ...

  7. idea中创建web项目搭建Hibernate框架连接oracle数据库

    hibernate框架 hibernate是数据化持久工具,也是一个开源代码的ORM解决方案.hibernate内部封装了通过jdbc访问数据库的操作,向商场应用提供面向对象的数据访问api. hib ...

  8. 连接Oracle数据库的Hibernate配置…

    连接Oracle数据库的Hibernate配置文件 连接Oracle的Hibernate配置文件有两种格式,一种是xml格式的,另一种是Java属性文件格式的.下面分别给出这两种格式配置文件的代码. ...

  9. hibernate简单连接mysql数据库配置

    使用hibernate连接mysql数据库 1:项目搭建好之后,在lib包中添加必要的jar包,和mysql数据库驱动jar包: jar包可以在hibernate的下载包(hibernate3.3.2 ...

随机推荐

  1. 201671010140. 2016-2017-2 《Java程序设计》java学习第十五周

    java学习第十五周 Java的GUI界面设计,框架以及主要部件填充,归置,布局管理,在第十一章和第十二章进行了系统的学习,在这两章的知识奠基下,可以简单的构造一个GUI用户界面,在两周的学习后,可以 ...

  2. linux开机自检配置文件fstab变只读无法修改问题

    控制linux开机自检的配置文件是/etc/fstab,在最近用的服务器中,发现fstab变成了只读权限,无法修改. 解决方法:RH5下,因磁盘改变,而导致系统停在Ctrl+d,此时需输入密码进入修改 ...

  3. if UNITY_EDITOR这个判断常用,还有哪个常用捏?

    #if DEVELOPMENT_BUILD || UNITY_EDITOR DEVELOPMENT_BUILD表示开发版的意思,会在程序右下角显示 Development Build 我们可以根据这个 ...

  4. Runnable和Thread实现多线程的区别(含代码)

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/17161237 Java中实现多线程有两种方法:继承Thread类.实现Runnable接口 ...

  5. fastDFS配置及日志查看 所遇到的问题

    FastDFS的配置文件在/usr/local/webserver/fastdfs/etc目录下,其中包括 client.conf    客户端上传配置文件 storage.conf    文件存储服 ...

  6. SqlServer——索引

    索引是根据表中一列或若干列按照一定顺序建立的列值与记录行之间的对应关系表.在数据库系统中建立索引主要有以下作用: l快速存取数据: l保证数据记录的唯一性: l实现表与表之间的参照完整性: l在使用O ...

  7. jquery验证简单示例

    来自<jquery 权威指南> 输入某个字符,选择相应的验证类型,并输出验证结果 ----------------------------------- 效果显示: 详细代码: <! ...

  8. logback与log4j比较

    摘自:https://www.cnblogs.com/smile361/p/7592684.html logback与log4j比较 更快的执行速度: 基于我们先前在log4j上的工作,logback ...

  9. git post-receive 待验证的代码

    使用 git post-receive 钩子部署服务端代码 本站文章除注明转载外,均为本站原创或者翻译. 本站文章欢迎各种形式的转载,但请18岁以上的转载者注明文章出处,尊重我的劳动,也尊重你的智商: ...

  10. yii2 Html::a

    Html::a($text,$url = null,$options = []) $url 可以直接是字符串 // An empty string. This will return the curr ...