简体   繁体   中英

Will an unchecked exception thrown and caught inside a method annotated with spring's @Transactional still cause the transaction to rollback?

I have method in my service class.

@Transactional
public void serviceMethod {
    dao.daoMethod();
}

public void daoMethod() {//dao.daoMethod
    //some code
    try {
        //some more code that throws an unchecked exception
    } catch(Exception exception) {
       //do something -- no exceptions generated/thrown from here
    }
    //some more code
 }

Will this result in the transaction rolling back? If the Unchecked exception was thrown from within a method that was called from the try block would it be any different?

No, the transaction will only be rolled back in case of an uncaught exception.

The transactional interceptors "wrap" around the calls of the annotated methods; they cannot see what happens inside them.

In your case it will silently ignore the exception. You didn't do anything inside the catch block. This is not advised at all.

If you catch an Exception in the try-catch block and you did some actions to handle this Exception - a rollback will not happen. In the case with RuntimeException, by default - the rollback will occur.

You can specify, which exceptions should cause the rollback. @Transactional(rollbackFor = MyCheckedException.class)

https://resourcepool.io/2014/11/16/java-quickies-what-you-wish-you-knew-about-spring-transactional-annotation/

https://www.catalysts.cc/wissenswertes/spring-transactional-rollback-on-checked-exceptions/

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