Spring--->声明式事务

回顾Mysql事务

  1. 原子性(要么全部完成,要么全部不起作用)
  2. 隔离性(操作同一个数据时,每一个事务应该隔离起来防止数据损坏)
  3. 持久性(事务一旦被提交就永久保存在服务器上)
  4. 一致性(所有事务动作全部完成,事务就要被提交,事务和资源保持一种满足业务规则的一致性)

 Spring 接管事务

注册beans

1、头文件约束导入

xmlns:tx="http://www.springframework.org/schema/tx" 

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

2、注册bean

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

3、配置事务相关通知

<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
       <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
       <tx:method name="add" propagation="REQUIRED"/>
       <tx:method name="delete" propagation="REQUIRED"/>
       <tx:method name="update" propagation="REQUIRED"/>
       <tx:method name="search*" propagation="REQUIRED"/>
       <tx:method name="get" read-only="true"/>
       <tx:method name="*" propagation="REQUIRED"/>
   </tx:attributes>
</tx:advice>
<!--添加注解支持-->
<tx:annotation-driven transaction-manager="transactionManager"/>

在对应的类上使用(一般为service层方法)

@Transactional
public void transfer() {
    ...
}

Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。

在一个方法执行过程中涉及多个事务,其中一个环节失败全部回滚,而不是提交一部分

REQUIRED:业务方法需要在一个事务中运行,如果方法运行时,已处在一个事务中,那么就加入该事务,否则自己创建一个新的事务。这是spring默认的传播行为。

SUPPORTS:该方法在某个事务范围内被调用,则方法成为该事务的一部分。如果方法在该事务范围外被调用,该方法就在没有事务的环境下执行。(查询)

4、配置切入点

<aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.xian.Mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor>
    </aop:config>

5、测试

 public void Test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper userDao = (UserMapper) context.getBean("userDao");
        List<User> user = userDao.getUser();
        for (User user1 : user) {
            System.out.println(user1);
        }
    }

事务的重要性

  • 如果不配置,就需要我们手动提交控制事务;

  • 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

原文地址:https://www.cnblogs.com/springxian/p/13726791.html