[Spring]11.Spring声明式事务

1.配置事务管理器

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

2.配置事务传播特性

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
  • tx:method name="get*"的意思是:所有get开头的方法,都开启事务。
  • propagation="REQUIRED"代表支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

这里同样要引入tx命名空间:

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    https://www.springframework.org/schema/tx/spring-tx.xsd">

3.配置aop

    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.wang.mapper.UserMapperImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>

4.测试
image
在getUser中添加操作:添加3号,删除2号
同时把删除的方法写错,使其报错。

在测试方法中调用getUsers()。
会发现添加和删除都没有成功执行,则说明getUser开启了事务。

posted @ 2021-11-27 20:05  从零开始学java_wxz  阅读(32)  评论(0)    收藏  举报