spring和mybatis整合进行事务管理

1、声明式实现事务管理

  XML命名空间定义,定义用于事务支持的tx命名空间和AOP支持的aop命名空间:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        
    <!-- 事务管理器,对mybatis操作数据库 控制。spring使用jdbc的事务控制类-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 :dataSource在dao中配置-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为,规范开发接口-->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
        
    <!-- 调用通知:aop -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* edu.mybatis.service.impl.*.*(..))"/>
    </aop:config>
</beans>

<bean id="transactionManager" class="...">用来定义事务管理器

<tx:advice>标签用于事务通知,用于指定事务,transaction-manager属性用来指定事务管理器,并且通过<tx:attributes>方法来指定具体需要拦截的方法

<tx:method name="save*">等方法是用来定义拦截一save头的方法,而且被拦截的方法应该配置事务属性:propagation="REQUIRED"表示传播行为是必须的,isolation:表示隔离级别,read-only=“true”,表示事务只读

<aop:config>声明进行Aop的配置,advice-ref属性用来指定通知,pointcut:用来定义切点

原文地址:https://www.cnblogs.com/googlemeoften/p/4699114.html