简体   繁体   中英

How to return different value, when transaction rollback?

I use ssh framework to develop a web application.

There is an example of my transaction.

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

Now, I want to return null when exception is thrown and then transaction rollback.

In general it is not advised to return null .

If you anticipate any Exception from your logic you should inform the caller via throws clause so that they are prepared for such scenarios.

Regarding rollback you should consider below update to your @Transactional annotation

@Transactional(rollbackFor=Exception.class)

Do note that this will rollback transaction after throwing any exception.

To rollback transaction programatically take a look at TransactionAspectSupport class.

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

You could do it declarative manner

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM