声明式事务
- 在 类或方法 上直接注解
@Transactional
遇到 RuntimeException
异常会自动回滚, 其他异常不会回滚
手动 catch
住的异常也不会回滚
@Transactional
public PmUserEntity create(PmUserEntity user) throws Exception {
user.setId(UUID.randomUUID().toString());
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
PmUserEntity save = pmUserRepository.save(user);
if (save != null)
throw new RuntimeException();
return save;
}
SpringBoot 快速开启事务(附常见坑点)
Spring声明式事务为何不回滚
编程式事务
//注入事务管理器
private final TransactionTemplate transactionTemplate;
@Autowired
public UserServiceImpl(PlatformTransactionManager transactionManager) {
Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
//包裹需要开启事务的代码块 transactionTemplate.execute(new TransactionCallback<PmUserEntity>() {
// public PmUserEntity doInTransaction(TransactionStatus status) {
//status.setRollbackOnly 用于回滚
public PmUserEntity createByTransactional(PmUserEntity user) throws Exception {
PmUserEntity execute = transactionTemplate.execute(new TransactionCallback<PmUserEntity>() {
public PmUserEntity doInTransaction(TransactionStatus status) {
user.setId(UUID.randomUUID().toString());
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
PmUserEntity save = pmUserRepository.save(user);
// status.setRollbackOnly();
return save;
}
});
return execute;
}
Spring框架事务管理之四:Spring编程式事务
Transaction Management
网友评论