tech_questions
tech_questions

Reputation: 273

Hibernate does not rollback in case of an exception thrown

I have below piece of code in my project. An exception is thrown at line # 4 still my product details are saved. I am having hard time to understand why does it save product details even after throwing the exception I am also trying to understand if the exception thrown at line #4 is a checked or unchecked exception ? If i am throwing "throw new Exception("Details don't match")" it is a Runtime exception I am assuming?

class Product{
    @Transactional
        addDetails(){
            try{
            }
            catch (Exception e) {
               throw new Exception("Details dont match") //Line 4
            }
           productDAO.save(productDetails) 
           addAdditionalDetails(productDetails)
        }
       }

class ProductDAO {
   @Transactional
   public void save(Product productDetails){
       entitiyManager.merge(productDetails)
   }
}

Upvotes: 0

Views: 1085

Answers (2)

Kunal
Kunal

Reputation: 389

With default spring configurations, only un-checked runtime exceptions are rolled back. In order to customize this configuration, rollbackFor is used as a property in the @Transactional annotation.

For ex,

@Transactional(rollbackFor = { MyInvalidUserException.class, MyApplicationException.class }) public void method() throws MyInvalidUserException, MyApplicationException { ... ... }

Upvotes: 0

Amit Bera
Amit Bera

Reputation: 7325

I am also trying to understand if the exception thrown at line #4 is a checked or unchecked exception?

Answer: java.lang.Exception is a checked exception.

If I am throwing "throw new Exception("Details don't match")" it is a Runtime exception I am assuming?

Answer: No, it is not a RuntimeException. RuntimeException is those which extends java.lang.RuntimeException or its subclass.

In spring by Transaction is Rollback when a Runtime exception occurs. That means any exception thrown in a transaction which extends RuntimeException or its subclass will rollback it. But in your case, you are throwing Exception which is not a type of RuntimeException.

Solution:

I will suggest creating a Custom exception which extends RuntimeExction and throws it.

class UnmatchedDetailException extends RuntimeException{
    UnmatchedDetailException(String msg){
        super(msg);
    }
}

And then throw the UnmatchedDetailException

throw new UnmatchedDetailException("Deatils not matched");

Upvotes: 2

Related Questions