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