美文网首页我爱编程
spring事务管理

spring事务管理

作者: LUNJINGJIE | 来源:发表于2018-04-09 11:12 被阅读0次
关于spring事务的用法分类如下:
1.png
在实际项目中比较常用的两种方法
1.基于AspectJ的XML方式(基于AOP思想)

在spring配置文件中配置,当程序运行时,spring会自动对<tx:method>中匹配的方法进行aop操作,进行所配置的事务管理

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <!--注入spring管理的dateSource-->
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--配置自动事务代理-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="transactionPointCut" expression="execution(* com.learn.service..*.*(..))" />
        <!--切面-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" />
    </aop:config>

    <!--配置事务增强处理Bean-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--方法自定义,把哪些方法纳入事务管理-->
            <!--可在此定义propagation传播行为、isolation、rollback-for等事务定义信息-->
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="persist*" propagation="REQUIRED" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
2.基于注解的事务管理

同样需要在spring配置文件中配置事务管理器,然后配置事务注解就ok了

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <!--注入spring管理的dateSource-->
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!--开启事务注解-->
    <tx:annotation-driven  transaction-manager="transactionManager"/>

然后再在需要添加事务的service层的所在类上添加@Transactional(propagation = Propagation.REQUIRED)注解即可,括号中为需要定义的事务信息


最后附上事务隔离级别以及传播行为相关定义
2.PNG 3.PNG

相关文章

网友评论

    本文标题:spring事务管理

    本文链接:https://www.haomeiwen.com/subject/bzdbhftx.html