jpganz18
jpganz18

Reputation: 5868

Will the rollbackFor attribute in Spring Data will work even if I do a try catch?

I was reading about the rollbackFor attribute when using JPA.

Right now my code is this

@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
   public void newUser(User user) {
        try{
            userRepository.saveAndFlush(user);
        }catch(Exception e){
            //log exception
        }
        return;
    }

As far as I know, the rollbackFor will work when an exception is captured... is this the proper way to do it? or the try catch should not be there?

Thanks.

Upvotes: 3

Views: 1571

Answers (1)

Vasu
Vasu

Reputation: 22442

Transactional Annotation rollbackFor: Defines zero (0) or more exception classes, which must be subclasses of Throwable, indicating which exception types must cause a transaction rollback.

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#rollbackFor--

Also, We should not suppress/eat the exception within the transactional method, rather we need to throw the Exception out from the method in order to roll back the database transaction:

Please find the proper implementation below:

     @Transactional(readOnly = false, 
      propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
      public void newUser(User user) throws Exception {
        try{
            userRepository.saveAndFlush(user);
         } catch(Exception e){
           throw new Exception("Unable to Save User Object ",e);
        }
     }

You can also refer the below link for handling exceptions for Transactional annotation:

Best practices for rolling back transactions in Spring 3/Hibernate

Upvotes: 2

Related Questions