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