spring + springmvc+ mybatis 事务管理及控制
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 对dataSource 数据源进行事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <!-- 事务管理 属性/通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 --> <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <!-- select,count开头的方法,开启只读,提高数据库访问性能 --> <tx:method name="select*" read-only="true"/> <tx:method name="count*" read-only="true"/> <!-- 对其他方法 使用默认的事务管理 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 事务 aop 配置/纳入 --> <aop:config> <aop:pointcut id="serviceMethods" expression="execution(* 包名..*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/> </aop:config> </beans>
将如上代码方法另存一个XML并在web.xml中引用,或直接加载在web.xml中。关于expression的详解 可以查看我的另一篇文章,里面有详解。
最简单的方法是先在spring配置文件里加上
1
|
< tx:annotation-driven transaction-manager = "transactionManager" /> |
再在Controller上使用spring的事务注解
也可以用AOP方式配置事务
1
2
3
4
5
6
|
< tx:advice id = "txAdvice" transaction-manager = "transactionManager" > < tx:attributes > <!--添加方法名称正则表达式以及事务属性--> < tx:method name = "*" propagation = "REQUIRED" read-only = "true" /> </ tx:attributes > </ tx:advice > |
1
2
3
4
5
6
|
< aop:config proxy-target-class = "true" > < aop:pointcut id = "aspectMethods" expression = "execution(* org.xxx.controller.*.*(..))" /> < aop:advisor advice-ref = "txAdvice" pointcut-ref = "aspectMethods" /> </ aop:config > |