Spring声明式事务管理方法

在上篇文章基础上用Spring事务管理功能:

1、首先导入以下jar包
Spring声明式事务管理方法_第1张图片

2、事务配置
在applicationContext.xml文件中添加以下内容:


<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory">property>
bean>

注意:这是作为公共使用的事务管理器Bean,是事先配置好的,不用各个模块各自去配置。

第一种方法:


<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="add*" propagation="REQUIRED" />
        <tx:method name="del*" propagation="REQUIRED" />
        <tx:method name="mod*" propagation="REQUIRED" />
        
        <tx:method name="*" propagation="REQUIRED" read-only="true" />
    tx:attributes>
tx:advice>


<aop:config>
    <aop:pointcut id="interceptorPointCuts"
        expression="execution(*   
       news.dao.*.*(..))" />
    
    <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
aop:config>

第二种方法:


<tx:annotation-driven transaction-manager="transactionManager"/>

用第二种方法还要指定在类上面添加@Transactional,或者指定到方法上添加,根据自己项目不同情况添加。本例如下图:
这里写图片描述

这里写图片描述

总结:这两种方法都是常用的,你可以根据你实际当中的项目情况选不同的方法。*重点内容*

你可能感兴趣的:(spring)