Spring事务管理介绍

 

一、声明式事务配置

 

1.基于TransactionProxyFactoryBean的配置

 

<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<import resource="classpath:applicationContext-dao.xml" />

<!--可以使用不同的事务管理器配置事务
org.springframework.jdbc.datasource.DataSourceTransactionManager
org.springframework.orm.JpaTransactionManager
org.springframework.orm.hibernate3.HibernateTransactionManager
org.springframework.orm.jdo.JdoTransactionManager
org.springframework.orm.jta.JtaTransactionManager
-->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="bbtForumTarget" 
	      class="com.baobaotao.service.impl.BbtForumImpl"
	      p:forumDao-ref="forumDao"
	      p:topicDao-ref="topicDao"
	      p:postDao-ref="postDao"/>

	<bean id="bbtForum"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
		p:transactionManager-ref="txManager"
		p:target-ref="bbtForumTarget">
		<property name="transactionAttributes">
			<props>
				<prop key="addTopic">
					PROPAGATION_REQUIRED,+PessimisticLockingFailureException
                </prop>
				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="*">PROPAGATION_REQUIRED,-tion</prop>
			</props>
		</property>
	</bean>
</beans>

 

 

2.基于scheme tx/aop命名空间和切面advisor配置

 

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	<import resource="classpath:applicationContext-dao.xml" />
	<bean id="bbtForum"
		class="com.baobaotao.service.impl.BbtForumImpl"
		p:forumDao-ref="forumDao"
		p:topicDao-ref="topicDao"
		p:postDao-ref="postDao"/>

	
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource"/>

	<aop:config>
		<aop:pointcut id="serviceMethod"
			expression="execution(* com.baobaotao.service.*Forum.*(..))" />
		<aop:advisor pointcut-ref="serviceMethod"
			advice-ref="txAdvice" />
	</aop:config>
	<tx:advice id="txAdvice" >
        <tx:attributes> 
            <tx:method name="get*" read-only="false"/>
            <tx:method name="add*" rollback-for="PessimisticLockingFailureException"/>
            <tx:method name="update*"/>         
        </tx:attributes>
    </tx:advice>
</beans>

 

3.基于注解@Transactional 及<tx:annotation-driven >自动配置

 

<?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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<import resource="classpath:applicationContext-dao.xml" />

	<bean id="bbtForum" 
	     class="com.baobaotao.service.impl.BbtForumImpl"
		 p:forumDao-ref="forumDao"
		 p:topicDao-ref="topicDao"
		 p:postDao-ref="postDao" />
		 
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource"/>

	<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
 	<!--名称为transactionManager可通过以下简化配置
	<bean id="transactionManager"
  		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  		p:dataSource-ref="dataSource"/>
 	<tx:annotation-driven/>
	-->
</beans>

 

相关的java注解类

@Transactional
public class BbtForumImpl implements BbtForum {
	private ForumDao forumDao;
	private TopicDao topicDao;
	private PostDao postDao;
	public void addTopic(Topic topic) throws Exception {
		topicDao.addTopic(topic);
//		if(true) throw new PessimisticLockingFailureException("fail");
		postDao.addPost(topic.getPost());
	}
	@Transactional(readOnly=true)
	public Forum getForum(int forumId) {
		return forumDao.getForum(forumId);
	}
	public void updateForum(Forum forum) {
		forumDao.updateForum(forum);
	}
	public int getForumNum() {
		return forumDao.getForumNum();
	}
	
	public void setForumDao(ForumDao forumDao) {
		this.forumDao = forumDao;
	}
	public void setPostDao(PostDao postDao) {
		this.postDao = postDao;
	}
	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}
}

 

4.通过AspectJ LTW引入事务切面,实现加截期间织入事务

 

使用-javaagent: org.springframework.aspects-{version}.jar作为JVM参数,在类路径META-INF目录下提供如下的配置文件:

<?xml version="1.0"?>
<aspectj>
	<aspects>
		<aspect
			name="org.springframework.transaction.aspectj.AnnotationTransactionAspect" />
	    </aspects>
	<weaver
		options="-showWeaveInfo -XmessageHandlerClass:org.springframework.aop.aspectj.AspectJWeaverMessageHandler">
		<include within="com.baobaotao.servie.impl.*" />
	</weaver>
</aspectj>

 

 

 

二、使用TransactonTemplate编程式的事务管理

 

<?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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
	http://www.springframework.org/schema/tx   
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
    
    <!-- jdbc事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref local="dataSource" />
		</property>
	</bean>
    <!--事务模板 -->
	<bean id="transactionTemplate"
		class="org.springframework.transaction.support.TransactionTemplate">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<!--ISOLATION_DEFAULT 表示由使用的数据库决定  -->
		<property name="isolationLevelName" value="ISOLATION_DEFAULT"/>
		<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
  		<!-- <property name="timeout" value="30"/> -->
	</bean>

</beans>

 

 

调用TransactionTemplate 相关java代码

 

protected TransactionTemplate transactionTemplate;
protected PayOrder savePayReq(final PayOrder payOrder) {
 PayOrder order = (PayOrder) this.transactionTemplate
   .execute(new TransactionCallback() {
    @Override
    public Object doInTransaction(TransactionStatus status) {
     ...
    }
   });
}

 

 三、通过DataSourceUtils获取数据连接,以避免数据连接泄漏

 

	Connection conn = null;
        try {
            //Connection conn = jdbcTemplate.getDataSource().getConnection();
            conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
            
            String sql = "UPDATE t_user SET last_logon_time=? WHERE user_name =?";
            jdbcTemplate.update(sql, System.currentTimeMillis(), userName);
            Thread.sleep(1000);//②模拟程序代码的执行时间
        } catch (Exception e) {
        	
            e.printStackTrace();
        }finally{
        	DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource());
        }

 

 

 其它技术相关的等价类:

SessionFactoryUtils

EntityManagerFactoryUtils

PersistenceManagerFactoryUtils

 

 

 

你可能感兴趣的:(Spring事务管理介绍)