Spring transaction: rollback on Exception or Throwable

前端 未结 4 2203
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 08:26

I wonder whether it makes sense to use instead of

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

to use

4条回答
  •  不知归路
    2020-12-05 08:42

    Since you are using @Transactional, we can safely assume you are doing your database operations through Spring, Hibernate, or other JDBC wrappers. These JDBC wrappers don't typically throw checked exceptions, they throw runtime exceptions that wrap the JDBC SQLException types.

    @Transactional is setup to rollback, by default, only when an unchecked exception is thrown.

    Consider a use case like so

    @Transactional
    public void persistAndWrite(Bean someBean) throws IOException {
        // DB operation
        getSession().save(someBean); 
    
        // File IO operation which throws IOException
        someFileService.writeToFile(someBean); 
    }
    

    You wouldn't necessarily want to rollback the DB operation just because we couldn't write something to a file.

    Similarly

    @Transactional
    public void persistAndThrowOutOfMemory(Bean someBean)  {
        // DB operation
        getSession().save(someBean);
    
        // consumes all memory, throws OutOfMemoryError
        someService.hugeOperationThrowsOutOfMemoryError(); 
    }
    

    You wouldn't necessarily want to rollback the saved entity just because some service cause too much memory to be consumed.

    @Transactional gives you the option. Use it where appropriate.

提交回复
热议问题