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

来源:互联网 发布:发现者行车记录仪淘宝 编辑:程序博客网 时间:2024/06/06 16:31

本文介绍针对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>


1 0
原创粉丝点击