简体   繁体   中英

Hibernate does not rollback in case of a runtime 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)
   }
}

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");

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 { ... ... }

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