JPA transaction rollback issue

 My project using Spring Boot, Spring Data JPA Spring which has a good package Affairs, in @Transactional notes, the transaction is performed automatically, abnormal automatic rollback, but when in use encounter some problems:

The method of execution error nesting time; use in multiple methods @Transactional, one of the ways to run time error, but the data insert, but the other two methods do not; sometimes throw an exception, but does not roll back ......

  After a review of some information, that is not correct to use Spring's @Transactional.

  I found examples of other people's blog in the following borrowed to illustrate how to use Spring's @Transactional in the end:

@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 {
        // transaction will still be submitted to 
        this.testSysConfig4(entity);
        throw new Exception("sysconfig error");
    } 
    
    the @Transactional (rollbackFor = Exception.class) 
    public void testSysConfig4 (SysConfigEntity the Entity) throws Exception { 
        
        this.saveSysConfig (the Entity); 
    } 
    
    
    
}

  

For commonly used summary @Transactional of Spring follows:

1. A method throws an exception within, the A method would have annotated 
2, a plurality of nested method calls, if there @Transactional notes, transaction propagation is generated, the default Propagation.REQUIRED 
3, if just write notes on the @ Transactional default rollback only RuntimeException rather than Exception rollback 
4, if you want to be checked Exceptions to roll back, you need to @Transactional (rollbackFor = Exception.class)

Guess you like

Origin www.cnblogs.com/Andrew520/p/12144362.html