您的位置:首页 > 编程语言 > Java开发

Spring框架事务管理之二:事务管理器与事务API的配置

2016-04-12 09:58 477 查看
本文介绍针对JDBC、Hibernate和JTA等事务API,Spring框架中如何进行XML配置。
1. 基于JDBC事务API的Spring XML配置
JDBC事务API依赖于具体的数据源,所以首先要在Spring的XML配置文件中设置数据源如下:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

然后,声明事务并引用数据源如下:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

2.基于Hibernate事务API的Spring XML配置
Hibernate事务API也依赖于具体的数据源,这被作为Hibernate SessionFactory的参数之一,用于创建Hibernate Session。所以Spring框架提供了特别的SessionFactory如下:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
</value>
</property>
</bean>
定义SessionFactory还需要其他参数。

声明事务时只要引用SessionFactory如下:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
补充:即使使用了Hibernate,Spring应用中仍然可以不使用Hibernate的事务API,而使用JTA事务API。

3.基于JTA事务API的Spring XML配置
JTA事务API依赖于JavaEE容器提供的数据源,这往往是通过JNDI获得的,所以无需在Spring的XML配置文件中为JTA事务API设置数据源,但是必须为其指明JNDI的URL,示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/jpetstore"/>

<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />

<!-- other <bean/> definitions here -->

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息