2014-11-24 50 views
0
配置两个数据库

我必须配置两个CFG文件来配置在同一个项目中的两个数据库,如何在Hibernate中

我试过,但它总是使用第一个配置文件,

可我知道怎么能我在同一个项目上使用两个数据库

回答

7

在您的代码中,您需要做的是为不同的数据库打开两个不同的会话工厂。 例如:

Configuration configA=new Configuration();//use the default hibernate.cgf.xml file 
Congiruration configB=new Configuration.configure('/hibernate_db2.cfg.xml') // use hibernate_db2.cfg.xml under root folder. 
SessionFactory sfa=configA.buildSessionFactory(); 
SessionFactory sfb=configB.buildSessionFactory(); 

现在,您可以使用不同的数据库打开不同的会话。

+0

谢谢你的评论,但在这之后我怎样才能得到会话中使用SFA和SFB?像 \t \t sf.openSession(); – 2014-12-02 12:11:41

+0

@Himanshu Sharma是的,您需要手动处理会话,这意味着打开会话和关闭会话。 – 2014-12-02 14:33:37

0

您需要有两个配置文件。

hibernate-mysql.cfg.xml 

hibernate-oracle.cfg.xml 

而代码应该是这样的。

MySQL配置

private static SessionFactory sessionAnnotationFactory; 

sessionAnnotationFactory = new Configuration().configure("hibernate-mysql.cfg.xml").buildSessionFactory(); 

Session session = sessionAnnotationFactory.openSession(); 

的Oracle SQL配置

sessionAnnotationFactory = new Configuration().configure("hibernate-oracle.cfg.xml").buildSessionFactory(); 

Session session = sessionAnnotationFactory.openSession()