spring默认事务管理:默认当一个方法出现RunTimeException(运行期异常)时会自动回滚事务。
有些时候,我们需要从业务上对spring事务进行控制,这时候,如果用spring的默认事务管理,事务没有回滚就达不到我们所期望的结果。
demo用的spring+mybatis+springmvc+mysql。
解决方法:
applicationContext-service.xml 中增删改方法加上rollback-for="MyException",当方法抛出自定义异常被spring接收,会回滚事务。
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
View Code
MyException 自定义异常类:
public class MyException extendsException {privateString message;publicString getMessage() {returnmessage;
}public voidsetMessage(String message) {this.message =message;
}publicMyException(String message) {super();this.message =message;
}publicMyException() {super();
}public MyException(String message, Throwable cause, boolean enableSuppression, booleanwritableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);
}publicMyException(String message, Throwable cause) {super(message, cause);
}publicMyException(Throwable cause) {super(cause);
}
View Code
ProMapper.java