在项目开发过程当中,若是您的项目中使用了Spring的@Transactional注解,有时候会出现一些奇怪的问题,例如:spring
明明抛了异常却不回滚?this
嵌套事务执行报错?spa
...等等code
不少的问题都是没有全面了解@Transactional的正确使用而致使的,下面一段代码就能够让你彻底明白@Transactional到底该怎么用。orm
直接上代码,请细细品味blog
@Service public class SysConfigService { @Autowired private SysConfigRepository sysConfigRepository; public SysConfigEntity getSysConfig(String keyName) { SysConfigEntity entity = sysConfigRepository.findOne(keyName); return entity; } public SysConfigEntity saveSysConfig(SysConfigEntity entity) { if(entity.getCreateTime()==null){ entity.setCreateTime(new Date()); } return sysConfigRepository.save(entity); } @Transactional public void testSysConfig(SysConfigEntity entity) throws Exception { //不会回滚 this.saveSysConfig(entity); throw new Exception("sysconfig error"); } @Transactional(rollbackFor = Exception.class) public void testSysConfig1(SysConfigEntity entity) throws Exception { //会回滚 this.saveSysConfig(entity); throw new Exception("sysconfig error"); } @Transactional public void testSysConfig2(SysConfigEntity entity) throws Exception { //会回滚 this.saveSysConfig(entity); throw new RuntimeException("sysconfig error"); } @Transactional public void testSysConfig3(SysConfigEntity entity) throws Exception { //事务仍然会被提交 this.testSysConfig4(entity); throw new Exception("sysconfig error"); } @Transactional(rollbackFor = Exception.class) public void testSysConfig4(SysConfigEntity entity) throws Exception { this.saveSysConfig(entity); } }
总结以下:事务
/** * @Transactional事务使用总结: * * 一、异常在A方法内抛出,则A方法就得加注解 * 二、多个方法嵌套调用,若是都有 @Transactional 注解,则产生事务传递,默认 Propagation.REQUIRED * 三、若是注解上只写 @Transactional 默认只对 RuntimeException 回滚,而非 Exception 进行回滚 * 若是要对 checked Exceptions 进行回滚,则须要 @Transactional(rollbackFor = Exception.class) * * org.springframework.orm.jpa.JpaTransactionManager * * org.springframework.jdbc.datasource.DataSourceTransactionManager * * org.springframework.transaction.jta.JtaTransactionManager * * * */