在spring boot 中,使用事务非常简单,直接在方法上面加入@Transactional 就可以实现,以下是我的做法
@GetMapping("delete") @ResponseBody @Transactional public void delete(@RequestParam("id") int id){</span><span style="color: #0000ff">try</span><span style="color: #000000"> {</br> </span><span style="color: #008000">//</span><span style="color: #008000">delete country</span></br> <span style="color: #0000ff">this</span><span style="color: #000000">.repository.delete(id);</br> </span><span style="color: #0000ff">if</span>(id == 1<span style="color: #000000">){</br> </span><span style="color: #0000ff">throw</span> Exception("测试事务"<span style="color: #000000">);</br> }</br> </span><span style="color: #008000">//</span><span style="color: #008000">delete city</span></br> <span style="color: #0000ff">this</span><span style="color: #000000">.repository.deleteByCountryId(id);</br> }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e){</br> logger.error(</span>"delete false:" +<span style="color: #000000"> e.getMessage());</br> </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> MessageBean(101,"delete false"<span style="color: #000000">);</br> }</br> }</span></pre>
发现事务不回滚,即 this.repository.delete(id); 成功把数据删除了。
原因:
默认spring事务只在发生未被捕获的 RuntimeException 时才回滚。
spring aop 异常捕获原理:被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认情况下aop只捕获 RuntimeException 的异常,但可以通过配置来捕获特定的异常并回滚
换句话说在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚
解决方案:
方案1.例如service层处理事务,那么service中的方法中不做异常捕获,或者在catch语句中最后增加throw new
RuntimeException()语句,以便让aop捕获异常再去回滚,并且在service上层(webservice客户端,view层action)要继续捕获这个异常并处理
方案2.在service层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常
1 @GetMapping("delete") 2 @ResponseBody 3 @Transactional 4 public Object delete(@RequestParam("id") int id){ 5 if (id < 1){ 6 return new MessageBean(101,"parameter wrong: id = " + id) ; 7 } 8 try { 9 //delete country 10 this.countryRepository.delete(id); 11 //delete city 12 this.cityRepository.deleteByCountryId(id); 13 return new MessageBean(200,"delete success"); 14 }catch (Exception e){ 15 logger.error("delete false:" + e.getMessage()); 16 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 17 return new MessageBean(101,"delete false"); 18 } 19 }