08-05
08

hibernate中使用多数据库

public   class   HibernateSessionFactory   {  
          private   static   SessionFactory   sessionFactory;  
    
          public   synchronized   static   Session   openSession_db1()   throws   HibernateException   {  
                  if   (sessionFactory   ==   null)   {  
                          init_db1();  
                  }  
                  return   sessionFactory.openSession();  
          }  
          public   synchronized   static   Session   openSession_db2()   throws   HibernateException   {  
                  if   (sessionFactory   ==   null)   {  
                          init_db2();    
                  }  
                  return   sessionFactory.openSession();  
          }  
    
          private   static   void   init_db1()   throws   HibernateException   {  
                  
  File   file   =   new   File("hibernate1.cfg.xml");    
  Configuration   conf   =   new   Configuration().configure(file);  
                  try   {                              
                          sessionFactory   =   conf.buildSessionFactory();  
                  }   catch   (MappingException   e)   {  
                          e.printStackTrace();  
                  }   catch   (HibernateException   e)   {  
                          e.printStackTrace();  
                  }  
          }  
    
    
          private   static   void   init_db2()   throws   HibernateException   {  
                  
  File   file   =   new   File("hibernate2.cfg.xml");    
  Configuration   conf   =   new   Configuration().configure(file);  
                  try   {                              
                          sessionFactory   =   conf.buildSessionFactory();  
                  }   catch   (MappingException   e)   {  
                          e.printStackTrace();  
                  }   catch   (HibernateException   e)   {  
                          e.printStackTrace();  
                  }  
          }  
  }  
    
  ================================  
  而在你的DAO中,获得Session的时候  
  连接数据库1  
    
                  Session   session1   =   HibernateSessionFactory.openSession_db1();  
                  Session   session2   =   HibernateSessionFactory.openSession_db2();  
      
  其他的都一样了。

文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: 多数据库
相关日志:
评论: 0 | 引用: 0 | 查看次数: 625
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭