学习杂记【1】关于spring JTA异常处理的rollback行为

spring的事务处理由aop处理,关于spring aop的学习和理解后续会写另一篇的文章,这里暂时不提。

我们通常在方法或者类上加上@Transcational将一个方法纳入spring事务管理,spring会在方法开始前开启一个事务,在方法执行完毕之后对内部的数据库操作进行commit或者rollback(成功就commit,失败就rollback咯)。

成功当然皆大欢喜,而失败则是我们需要了解的地方。先说结论:
以下几句话意思大致接近:

  • spring默认会对方法内部抛出的非受检异常(unchecked exception)做rollback处理。
  • 方法内部抛出的受检异常(checked exception)或者吞掉了非受检异常,spring事务会失效。

非受检一般包括Error和RunTimeException,抛开Error,那么就是说spring事务回滚是看是不是抛出RunTimeException。
那么关于异常处理用到的try catch代码块就需要稍加注意:
1⃣️不要私吞exception(catch之后只打打log这种操作)
2⃣️如果遇到受检异常比如说IOException时,如果需要让事务依然生效,请使用

@Transactional(rollbackFor=Exception.class)

最后:
spring文档对此的解释是:

While the EJB default behavior is for the EJB container to automatically roll back the transaction on a system exception (usually a runtime exception), EJB CMT does not roll back the transaction automatically on an application exception (that is, a checked exception other than java.rmi.RemoteException). While the Spring default behavior for declarative transaction management follows EJB convention (roll back is automatic only on unchecked exceptions), it is often useful to customize this.

实话说我没看到更深的东西,感觉就是spring希望我们使用unchecked exceptions来维护事务,希望理解更深的同学可以解释解释。

你可能感兴趣的:(学习杂记【1】关于spring JTA异常处理的rollback行为)