在项目开发过程中,如果您的项目中使用了Spring的@Transactional注解,有时候会出现一些奇怪的问题,例如:
明明抛了异常却不回滚?
嵌套事务执行报错?
...等等
很多的问题都是没有全面了解@Transactional的正确使用而导致的,下面一段代码就可以让你完全明白@Transactional到底该怎么用。
直接上代码,请细细品味
@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事务使用总结:
*
* 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
*
*
*
*/