Spring和hibernate多个数据源的事务管理
1、准备工作
我的项目是struts2+spring+hibernate架构,web服务用tomcat;
现在遇到的问题是要连接多个数据库一个Oracle一个SqlServer,现在把我配置过程分享给大家!
使用jta事务,用tomcat+jotm提供事务管理器
请先下载相应的jotm的jar包,放到工程中的lib包中
2、配置hibernate配置文件,有几个数据库就配几个这样的文件
我的配sqlserver数据库的文件如下:
例如:hibernate_sqlserver.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.username">sa</property>
<property name="connection.url">jdbc:microsoft:sqlserver://192.168.0.100:1433;DatabaseName=PrisonSoftWeb1
</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">test</property>
<property name="connection.password">server</property>
<property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver
</property>
</session-factory>
<hibernate-configuration>
其他数据库和其类似!
3、配置sping::applicationContext.xml中添加相应的session工厂
(1)以下两个bean用于spring对jotm初始化
<bean id="jotm" lazy-init="true" lazy-init="true" />
</property>
</bean>
<!-- sqlserver 数据库sessionFactory -->
<bean id="sessionFactoryForSqlServer" />
</property>
</bean>
(3)为dao注入对应的session工厂
<bean id="sqlServerbaseDao" />
</property>
</bean>
4、手动提交:Dao实现中采用手动提交和回滚事务的办法,避免数据库因事务不能及时提交而引起死锁现象
this.getSession().clear();
Transaction tx = null;
try{
tx = this.getSessionFactory().getCurrentSession().beginTransaction();
//这里写你的操作数据库的代码:例如:
this.getHibernateTemplate().update(objBean);
tx.commit();
}catch(RuntimeException e){
if(tx != null)tx.rollback();
throw e;
}finally{
//this.getSession().close();
}