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

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

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

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

代码如下:

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



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

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