事务回滚时如何return不同的值?

How to return different value, when transaction rollback?

我使用 ssh 框架开发一个 web 应用程序。

有我交易的例子。

@Transactional
public StudentEntity addStudent(StudentEntity studentEntity) {
       return studentDAO.save(studentEntity);
}

现在,我想在抛出异常return null然后事务回滚。

要以编程方式回滚事务,请查看 TransactionAspectSupport class。

@Transactional
public StudentEntity addStudent(StudentEntity studentEntity) {
      try {
       return studentDAO.save(studentEntity);
        }
      catch(Exception ex) {
       //set transaction for rollback.
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
     }
}

你可以用声明的方式来做

@Transactional(rollbackFor={SomeSpecificException.class, SomeOtherSpecificException.class}) 

一般不建议returnnull

如果您从您的逻辑中预期任何 Exception,您应该通过 throws 子句通知调用者,以便他们为此类情况做好准备。

关于回滚,您应该考虑在下方更新您的 @Transactional 注释

@Transactional(rollbackFor=Exception.class)

请注意,这将在抛出任何异常后回滚事务。