1.声明式事务
1.1回顾事务
-
要么都成功,要么都失败
-
确保数据的一致性和完整性,所以十分重要
-
事务的ACID原则
- 原子性
- 一致性
- 隔离性
- 多个业务操作同一个事务,防止数据损坏
- 持久性
- 事务一旦提交,结果都不会再被影响
1.2Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中进行事务的管理
1.配置文件要导入事务的约束(beans约束、aop约束、tx事务约束)
每个约束都要在xmlns配置和xsi:schemaLocation里配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
.......
</beans>
2.在配置文件配置声明式事务
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 有构造可以直接传参-->
<constructor-arg ref="datasource" />
<!-- 有set方法也可以这样-->
<!-- <property name="dataSource" ref="datasource"/>-->
</bean>
3.结合aop织入
<!-- 结合aop实现事务的织入-->
<!-- 配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 给那些方法配置事务-->
<!-- 配置事务传播特性: new propagation,默认都是REQUIRED-->
<tx:attributes>
<!-- 给所有添加方法配置事务-->
<tx:method name="add" propagation="REQUIRED"/>
<!-- 给所有删除方法配置事务-->
<tx:method name="delete" propagation="REQUIRED"/>
<!-- 给所有查询方法配置事务-->
<tx:method name="query" read-only="true"/>
<!-- 给所有方法配置事务-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
- Spring中七种Propagation类的事务属性详解:
配置 | 介绍 |
---|---|
REQUIRED | 支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择 |
SUPPORTS | 支持当前事务,如果当前没有事务,就以非事务方式执行 |
MANDATORY | 支持当前事务,如果当前没有事务,就抛出异常 |
REQUIRES_NEW | 新建事务,如果当前存在事务,把当前事务挂起 |
NOT_SUPPORTED | 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起 |
NEVER | 以非事务方式执行,如果当前存在事务,则抛出异常 |
NESTED | 支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务 |
4.配置事务切入
<!-- 配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* mapper.UserMapper.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
5.测试
5.1在查询的方法中插入嵌套其他方法,来测试当方法部分执行出错的时候,事务是否会回滚
@Override
public List<User> selectuser() {
User user = new User(5, "小王", "123123");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(4);
return mapper.selectuser();
}
5.2直接测试
public class mytest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
for (User user:
userMapper.selectuser()) {
System.out.println(user);
}
}
}
Spring5完结!