简体   繁体   中英

Hibernate saveAndFlush not persisted when application exception is thrown

I hope someone has come across this issue:

In the service layer I am catching an exception and in the catch block I want to save a record in the database calling saveAndFlush and then throwing the application exception. The issue is that the save and flush doesn't persist the record and the transaction seems to rollback.

The code is something like that:

catch(SomeException e) {
   repoClass.saveAndFlush(entity);
   throw new ApplicationException();
}

Any thoughts?

Many thanks.

It is because spring will roll back the transaction if the code throws any RuntimeException , ApplicationException is a RuntimeException hence saveAndFlush not working (Transaction rolled back).

In your case you have to throw a UserDefinedException instead of the RuntimeException

sample

public class UserDefinedException extends Exception {

}

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