2014-11-24 56 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()