1. 编程方式的事务声明
Spring也为我们提供了模板类TransactionTemplate进行事务管理
2 .声明式的事务声明
1.基于tx和aop命名空间的xml配置文件
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert" propagation="REQUIRED" read-only="false" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pointCut" expression="execution (* com.gray.service.*.*(..))"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointCut"/>
</aop:config>
2.基于@Transactional注解
这种方式最简单,也是最为常用的,只需要在配置文件中开启对注解事务管理的支持。
<!-- 声明式事务管理 配置事物的注解方式注入-->
<tx:annotation-driven transaction-manager="transactionManager"/>
- 然后在需要事务管理的地方加上@Transactional注解,如:
@Transactional(rollbackFor=Exception.class)
public void insert(String sql, boolean flag) throws Exception {
dao.insertSql(sql);
// 如果flag 为 true ,抛出异常
if (flag){
throw new Exception("has exception!!!");
}