声明式事务管理

方式一,全在spring配置

spring 中的配置文件:

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</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.service.*.*(..))" /><!-- 语法:(* packageName.*.*(..) 第二个*为类名,第三个*为方法名 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
</aop:config>

方式二,部分在源码中配置:

spring中的配置:

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

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

源码中的配置:

@Transactional(readOnly=true)//可在方法名上配置
public List showAllNews() {

@Transactional//也可在类名上配置,即类中所有方法都会添加事务
public class NewsServiceImpl implements NewsService {

方法优缺点:

方法一 方法二
在spring配置文件中一次性配置,编程人员比较轻松 需要到具体的类或方法配置,较麻烦
较低的阅读性 较高的阅读性
降低了耦和性,项目更好管理 增加了耦合性,项目不好管理

最后,具体用哪种方法看情况而定,本文纯属个人学习经验,如有不正之处,还望指正,感激不尽。
(虽然没什么人看 /(ㄒoㄒ)/~~)

文章目录
  1. 1. 方式一,全在spring配置
  2. 2. 方式二,部分在源码中配置:
|