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

3次阅读

共计 1063 个字符,预计需要花费 3 分钟才能阅读完成。

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 来保护事务,心愿了解更深的同学能够解释解释。

正文完
 0