hibernate链接两个数据库查询

来源:互联网 发布:增加力量 知乎 编辑:程序博客网 时间:2024/06/05 02:13


hibernate可链接两个不同的数据库,可以都是mysql或者一个mysql一个sql seiver等;


具体如下:

一、(在src下)写两个Hibernate.cfg.xml文件: 如 hbn-mysql.cfg.xml和hbn-sqlserver.cfg.xml 
二、分别解析上面的两个.cfg.xml文件建两个sessionFactory, 
三、使用session时哪个sessionFactory打开的session就能访问哪个数据库。 


(1.)hbn-mysql.cfg.xml的内容:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<!--hibernate配置文件,定义所使用的MySQL数据库的配置信息 -->
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping
   resource="com/fourstar/starTransport/daomain/orderIdStatus.hbm.xml" />
<mapping
   resource="com/fourstar/starTransport/daomain/freightCompany.hbm.xml" />
</session-factory>
</hibernate-configuration>

(2.)hbn-sqlserver.cfg.xml的内容:

<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="connection.driver_class">
   com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="connection.url">jdbc:sqlserver://192.168.2.16:1433; DatabaseName=test</property>
<property name="connection.username">sa</property>
<property name="connection.password">root</property>
<property name="connection.isolation">2</property>
<property name="dialect">
   org.hibernate.dialect.SQLServerDialect
</property>
<mapping
   resource="com/fourstar/starTransport/daomain/transactions.hbm.xml" />
   <mapping
   resource="com/fourstar/starTransport/daomain/transactionDetail.hbm.xml" />
</session-factory>
</hibernate-configuration>

mysql默认端口为3306,sql server为1143,链接某种数据库都必须加入其驱动

备注:一个数据库需要有自己的一个session供增删改,所以有多少个数据库必须用sessionFactory创建多少个session,再使用自我的session进行操作

0 0
原创粉丝点击