回滚后需要新事务仍影响实体

RequiresNew transaction after rolling back still affect entity

提问人:Andrzej Więcławski 提问时间:11/6/2023 更新时间:11/6/2023 访问量:11

问:

上下文:spring boot 2.7.0 ,@EnableTransactionManagement主应用程序类

假设:未选中的异常应该回滚内部事务,但既然被捕获了,就不会影响外部事务。

使用的解决方案:

@Service
class ExternalService {
  final InnerService innerService;

  @Transactional(propagation = Propagation.REQUIRED)
  public User requiredRequired(User user) {
    user = userRepository.save(user);
    try {
      innerService.doRequired(user);
    } catch (RuntimeException e) { 
    // error handling
    }
    return user;
  }
}

@Service
public class InnerService {
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  
  public void doRequiresNew(User user) {
    affectUser(user);
    // if condition then:
    throw new RuntimeException("Rollback this 'doRequiresNew' transaction!");
    }

    private void affectUser(User user) {
    // change something in User .ex:
    user.setFirstName(user.getFirstName() + "_affected!");
  }
}

输入:User(firstName=Lolek, lastName=Bolek)

数据库中的结果:User(id=1, createdAt=2023-11-05T17:03:23.324309Z, firstName=Lolek_affected!, lastName=Bolek)

问题:为什么新交易的结果仍然保留?

PS.只有当方法有注释时,它才有效InnerService@Transactional (propagation = Propagation.NESTED)

spring-boot 事务 回滚 传播

评论


答: 暂无答案