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