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


 

在項目開發過程中,如果您的項目中使用了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
         * 
         * 
         * 
         */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM