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

时间:2015-01-23 03:22:36

标签: java spring ssh transactions

我使用ssh框架开发Web应用程序。

有一个我的交易的例子。

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

现在,我想在异常被抛出然后事务回滚时返回null

2 个答案:

答案 0 :(得分:1)

一般情况下,建议不要返回null

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

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

@Transactional(rollbackFor=Exception.class)

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

答案 1 :(得分:0)

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

@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}) 
相关问题