1.事务何时回滚java
默认spring事务只在发生未被捕获的 runtimeexcetpion时才回滚。
spring aop 异常捕获原理:被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认状况下aop只捕获runtimeexception的异常,但能够经过
配置来捕获特定的异常并回滚
换句话说在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚
解决方案:
方案1.web
例如service层处理事务,那么service中的方法中不作异常捕获,或者在catch语句中最后增长throw new RuntimeException()语句,以便让aop捕获异常再去回滚,而且在service上层(webservice客户端,view层action)要继续捕获这个异常并处理
方案2.spring
在service层方法的catch语句中增长:app
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常(如今项目的作法)ide
RuleBasedTransactionAttribute /** * Winning rule is the shallowest rule (that is, the closest in the * inheritance hierarchy to the exception). If no rule applies (-1), * return false. * @see TransactionAttribute#rollbackOn(java.lang.Throwable) */ @Override public boolean rollbackOn(Throwable ex) { if (logger.isTraceEnabled()) { logger.trace("Applying rules to determine whether transaction should rollback on " + ex); } RollbackRuleAttribute winner = null; int deepest = Integer.MAX_VALUE; if (this.rollbackRules != null) { for (RollbackRuleAttribute rule : this.rollbackRules) { int depth = rule.getDepth(ex); if (depth >= 0 && depth < deepest) { deepest = depth; winner = rule; } } } if (logger.isTraceEnabled()) { logger.trace("Winning rollback rule is: " + winner); } // User superclass behavior (rollback on unchecked) if no rule matches. if (winner == null) { logger.trace("No relevant rollback rule found: applying default rules"); return super.rollbackOn(ex); } return !(winner instanceof NoRollbackRuleAttribute); }
//经过源码能够看出,spring默认只对,RuntimeException和Error作处理了 DefaultTransactionAttribute @Override public boolean rollbackOn(Throwable ex) { return (ex instanceof RuntimeException || ex instanceof Error); }