Hibernate如何配置操作多個數據庫
Question:
引用:
我現在在做一個項目,需要從兩個數據庫實例中存取數據,在用hibernate實現的過程中該如何配置和處理
--------------------------------------------------------------------------------
1、如果一個項目要從兩個乃至多個數據庫實例讀取數據,該如何處理?
2、如果只有一個數據庫oraA,為其建立建立oraA.hbm.xml以及hibernate.properties文件,該文件中的數據庫連接部分寫為:
## Oracle
hibernate.dialect net.sf.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username username
hibernate.connection.password password
hibernate.connection.url jdbc:oracle:thin:@local:1521:ora
3、如有兩個oracle數據庫oraA和oraB,分別為其建立oraA.hbm.xml和oraB.hbm.xml映射文件,這樣數據庫中的各個表和實體持久化類就可以映射好,但是hibernate.properties中的數據庫配置部分該如何處理呢,怎樣才能同時連接上兩個數據庫實例呢?
如果用這個Configuration.configure(File configFile)
configFile可以是不同的配置。
通過配置configFile可以得到每個數據庫的configuration, 也就是可以獲得每個數據庫實例的session;但是在hibernate.properties文件中怎么寫數據庫連接部分呢,一個數據庫的時候寫法是:hibernate.connection.url jdbc:oracle:thin:@local:1521:ora
那如果有兩個數據庫實例呢,在hibernate.properties文件中怎么處理,總不會是寫成如下吧:
##oracle
hibernate.dialect net.sf.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username username
hibernate.connection.password password
hibernate.connection.url jdbc:oracle:thin:@local:1521:oraA
hibernate.connection.username usernamet
hibernate.connection.password passwordt
hibernate.connection.url jdbc:oracle:thin:@local:1521:oraB
Answer:
寫兩個hibernate.properties,例如連接oraA的叫做hibernateA.properties,連接oraB的叫做hibernateB.properties。
hibernateA.properties內容如下:
引用:
hibernate.dialect net.sf.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username username
hibernate.connection.password password
hibernate.connection.url jdbc:oracle:thin:@local:1521:oraA
hibernateB.properties內容如下:
引用:
hibernate.dialect net.sf.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username usernamet
hibernate.connection.password passwordt
hibernate.connection.url jdbc:oracle:thin:@local:1521:oraB
程序里面:
代碼:
java代碼:
Configuration conf_oraA = new Configuration("/hibernateA.properties").addClass().......;
Configuration conf_oraB = new Configuration("/hibernateB.properties").addClass().......;
SessionFactory sf_oraA = conf_oraA.buildSessionFactory();
SessionFactory sf_oraB = conf_oraB.buildSessionFactory();
Session s_oraA = sf_oraA.openSession();
Session s_oraB = sf_oraB.openSession();
......
---------------------------------------------------------------
更正一下
方案一:
寫兩個hibernate.cfg.xml
使用數據庫a的時候
Configuration cfg_a=new Configuration().configure(hibernate.cfg_a.xml);
使用數據庫b的時候
Configuration cfg_b=new Configuration().configure(hibernate.cfg_b.xml);
usr/home/zk1007874/htdocs/upload_files/images
方案二:
使用一個能操作兩個數據庫的賬號,在?.hbm.xml映射文件中的class標簽中指定catalog為數據庫名