ANWESH MOHAPATRA
ANWESH MOHAPATRA

Reputation: 317

Spring JPA: Unexpected rollback exception hides the actual exception I need to handle

I am experimenting with @transactional in spring boot. I have written a service with multiple table insertions and I want the entire thing to rollback if there is any exception.
This works fine but rather than throwing the actual exception that caused the rollback, I am getting Unexpected Rollback Exception

@transactional
public void insertIntoTables(){
    repositoryone.save(new Table1());
    repositorytwo.save(new Table2()); //expecting data integrity violation exception on this line
}

Rather than throwing the DataIntegrityViolationException, the above code throws Unexpected Rollback Exception. I want the rollback to happen ofcourse, just want to avoid the exception so that I can use the actual one.
How to get the actual exception for handling purposes?

Upvotes: 1

Views: 2883

Answers (1)

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

Even I faced similar issue before. I handled it by adding rollback for. Below is how I handled it.

  1. Imported org.springframework.transaction.annotation.Transactional
  2. Then instead of @Transactional, I used @Transactional(rollbackFor = Exception.class) above my service methods

This will handle any runtime exception. So, DataIntegrityViolationException should be displayed to user.

Upvotes: 2

Related Questions