Spring 事务
特性
ACID:原子性,一致性,隔离性,持久性。
事务是一个不可分割的操作,其中的过程要么全部成功要么全部失败。一旦完成后会统一提交来保证一致性。
不同的事务处理统一数据是隔离的,防止数据的损坏。事务的结果会被永久的保存。
分类
- 编程式事务
缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
- 声明式事务
将事务管理作为横切关注点,通过aop方法模块化。
编程式事务
public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper{
private final PlatformTransactionManager transactionManager;
public UserMapperImpl1(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public List selectUser() {
return getSqlSession().getMapper(UserMapper.class).selectUser();
}@Override
public int addUser(User user) {
int a=0;
TransactionStatus txStatus =
transactionManager.getTransaction(new DefaultTransactionDefinition());
try{
getSqlSession().getMapper(UserMapper.class).addUser(user);
getSqlSession().getMapper(UserMapper.class).deleteUser(10);
}catch (Exception e){
transactionManager.rollback(txStatus);
throw e;
}
return a;
}
/* 此处和上述一致
//TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
//a = transactionTemplate.execute(txStatus -> {
//getSqlSession().getMapper(UserMapper.class).addUser(user);
//getSqlSession().getMapper(UserMapper.class).deleteUser(10);
//return null;
//});
@Override
public int deleteUser(Integer id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
声明式事务
常用两种传播方式:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。
JAVA类:
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List selectUser() {
int a1 = getSqlSession().getMapper(UserMapper.class).addUser(new User(12,"wxn1"));
return getSqlSession().getMapper(UserMapper.class).selectUser();
}@Override
public int addUser(User user) {
System.out.println("新增开始");
int a = getSqlSession().getMapper(UserMapper.class).addUser(user);
System.out.println("新增结束");
return a;
}@Override
public int deleteUser(@Param(value = "https://www.it610.com/article/id") Integer id) {
System.out.println("删除开始");
int a1 = getSqlSession().getMapper(UserMapper.class).addUser(new User(12,"wxn1"));
int a2 = getSqlSession().getMapper(UserMapper.class).deleteUser(id);
System.out.println("删除结束");
return a2;
}
}
【Spring 事务】测试类:
public void selectUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
//userMapper.addUser(new User(8,"丽丽1"));
//userMapper.deleteUser(10);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}