JPA的事務註解@Transactional使用總結

 

在項目開發過程當中,若是您的項目中使用了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
         * 
         * 
         * 
         */
相關文章
相關標籤/搜索