spring控制事务:声明式事务(XML)事务的传播行为

29 篇文章 0 订阅

声明式事务(XML)

使用spring提供的专用于mybatis的事务管理器在xml中声明式事务

声明式事务需要使用到的标签

tx配置

进行<tx 标签的使用需要在xml头部导入命名空间

xmlns:tx="http://www.springframework.org/schema/tx" 
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
声明式事务需要用到的事务管理器类
<!--    将事务管理器交给ioc管理-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<!--    从ioc中获取DataSource-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
< tx:advice> 标签

⚫ 名称:tx:advice
⚫ 类型:标签
⚫ 归属:beans标签
⚫ 作用:专用于声明事务通知
⚫ 格式:

<beans>
	<tx:advice id="txAdvice" transaction-manager="txManager">
	</tx:advice>
</beans>

⚫ 基本属性:
◆ id :用于配置aop时指定通知器的id
◆ transaction-manager :指定事务管理器bean

< tx:attributes> 标签

⚫ 名称:tx:attributes
⚫ 类型:标签
⚫ 归属:tx:advice标签
⚫ 作用:定义通知属性
⚫ 格式:

<tx:advice id="txAdvice" transaction-manager="txManager">
	<tx:attributes>
	</tx:attributes>
</tx:advice>

⚫ 基本属性:
◆ 无

< tx:method>标签

名称:tx:method
⚫ 类型:标签
⚫ 归属:tx:attribute标签
⚫ 作用:设置具体的事务属性
⚫ 格式:

<tx:attributes>
	<tx:method name="*" read-only="false" />
	<tx:method name="get*" read-only="true" />
</tx:attributes>

⚫ 说明:
通常事务属性会配置多个,包含1个读写的全事务属性,1个只读的查询类事务属性

tx:method属性 争对方法配置不同方法的事务信息
<!--             <tx:method/>可以配置多个
        <tx:method
        name="*"                待添加事务的方法名表达式(支持*号通配符),例如get** 、……
        read-only="false"       设置事务的读写属性,true为只读,false为读写
        timeout="-1"            设置事务超时时长,单位秒
        isolation="DEFAULT"     设置事务隔离级别,该隔离级设定是基于Spring的设定,非数据库端
        no-rollback-for=""      设置事务中不回滚的异常,多个异常间使用,分割
        rollback-for=""         设置事务中必回滚的异常,多个异常间使用,分割
        propagation="REQUIRED"  设置事务的传播行为
        />
-->

模板

⚫ 使用tx命名空间配置事务专属通知类

<tx:advice id="txAdvice" transaction-manager="txManager">
	<tx:attributes>
		<tx:method name="*" read-only="false" />
		<tx:method name="find*" read-only="true" />
	</tx:attributes>
</tx:advice>

⚫ 使用aop:advisor在AOP配置中引用事务专属通知类

<aop:config>
	<aop:pointcut id="pt" expression="execution(* *..*(..))"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>

转账案列进行事务管理(xml声明式事务)

mysql数据表

下面的案列就是对这两个数据进行更新的事务管理
在这里插入图片描述

搭建一个maven项目

在这里插入图片描述

pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.fs</groupId>
    <artifactId>day04_spring_AOP_Transaction_01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!--        jdbc-->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!--        spring整合mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--        aop切面包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
配置文件(主配置文件中有详细的注释解释)
applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    扫描spring的注解-->
    <context:component-scan base-package="com.fs"/>
<!--    读取类路径下的.properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>


<!--    配置链接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--    配置MyBatis-->
<!--    配置SqlSession的会话工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置MyBatis动态代理映射对象-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.fs.dao"/>
    </bean>


<!--    声明式事务(XML)-->
<!--    将事务管理器交给ioc管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    定义事务管理的通知类 ,配置不同方法的事务信息
 命名空间xmlns:tx="http://www.springframework.org/schema/tx"-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
<!--             <tx:method/>可以配置多个
        <tx:method
        name="*"                待添加事务的方法名表达式(支持*号通配符),例如get** 、……
        read-only="false"       设置事务的读写属性,true为只读,false为读写
        timeout="-1"            设置事务超时时长,单位秒
        isolation="DEFAULT"     设置事务隔离级别,该隔离级设定是基于Spring的设定,非数据库端
        no-rollback-for=""      设置事务中不回滚的异常,多个异常间使用,分割
        rollback-for=""         设置事务中必回滚的异常,多个异常间使用,分割
        propagation="REQUIRED"  设置事务的传播行为
        />
-->
<!--   *代表所有方法   该事务是只读的吗? false不是      -->
            <tx:method name="*" read-only="false"/>
<!--     find*  代表find开头的所有方法只读       -->
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

<!--    配置aop-->
    <aop:config>
<!--        配置切入点 注意切入点表达式是否正确-->
        <aop:pointcut id="pt" expression="execution(* com.fs.service.impl.*.*(..))"/>
<!--        使用aop:advisor在AOP配置中引用事务专属通知类-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>
</beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.93.132:3306/test
jdbc.username=root
jdbc.password=root
pojo 实体类
Account
package com.fs.pojo;

import lombok.Data;

@Data
public class Account {
    private Integer id;
    private String name;
    private Double money;
}

dao
AccountDao
package com.fs.dao;

import com.fs.pojo.Account;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface AccountDao {
    @Select("select * from account")
    List<Account> findAll();//查询所有

    //根据名字修改money
    @Update("UPDATE account SET money = #{money} WHERE name = #{name}")
    void transferMoney(Account account);

    //根据名字查询账户信息
    @Select("select * from account where name = #{name}")
    Account findAccountByName(@Param("name") String name);
}

service
AccountService
package com.fs.service;

import com.fs.pojo.Account;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface AccountService {
    List<Account> findAll();

    Account findAccountByName(String name);

    void transferMoneyAtoB(String aName,String bName,Integer money);
}

impl.AccountServiceImpl 代码中有spring事务管理器在业务层硬编码进行事务管理的代码(注释了)

在业务类中,我也使用编码的方式对spring的业务层进行了事务控制(注释代码就是)

package com.fs.service.impl;

import com.fs.dao.AccountDao;
import com.fs.pojo.Account;
import com.fs.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.util.List;

/*
    <!--  把业务类 AccountServiceImpl 交给ioc管理 -->
    <bean id="accountServiceImpl" class="com.fs.service.impl.AccountServiceImpl">
<!--       依耐注入dao,这个dao被MyBatis动态代理实现后被spring存放在ioc容器中-->
        <property name="accountDao" ref="accountDao"/>
    </bean>
 */
@Service
public class AccountServiceImpl implements AccountService {

    //从ioc获取MyBatis动态代理的accountDao实现类
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private DataSource dataSource;


    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public Account findAccountByName(String name) {
        return null;
    }

    /*
    ⚫ 使用spring提供的专用于mybatis的事务管理器在业务层硬编码进行事务管理
    ⚫ 业务层要注入dataSource对象

    //转账的业务实现
    @Override
    public void transferMoneyAtoB(String aName, String bName, Integer money) {
        //先查出两个人的数据
        Account aAccount = accountDao.findAccountByName(aName);
        Account bAccount = accountDao.findAccountByName(bName);

        //然后a减钱,b加钱
        aAccount.setMoney(aAccount.getMoney()-money);
        bAccount.setMoney(bAccount.getMoney()+money);

        //编程调用事务
        //开启事务,使用Spring的平台事务管理器,是一个接口,使用他的实现类构造器传递一个连接池
        PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);
        //创建事务定义对象
        TransactionDefinition td = new DefaultTransactionDefinition();
        //创建事务状态对象,用于控制事务执行
        TransactionStatus ts = ptm.getTransaction(td);

        //然后调用转账方法(sql语句为更新账户)
        accountDao.transferMoney(aAccount);
        //制作一个异常
        int i = 1/0;
        accountDao.transferMoney(bAccount);

        //提交事务
        ptm.commit(ts);
    }

     */


    //转账的业务实现
    @Override
    public void transferMoneyAtoB(String aName, String bName, Integer money) {
        //先查出两个人的数据
        Account aAccount = accountDao.findAccountByName(aName);
        Account bAccount = accountDao.findAccountByName(bName);

        //然后a减钱,b加钱
        aAccount.setMoney(aAccount.getMoney()-money);
        bAccount.setMoney(bAccount.getMoney()+money);


        //然后调用转账方法(sql语句为更新账户)
        accountDao.transferMoney(aAccount);
        //制作一个异常
        //int i = 1/0;
        accountDao.transferMoney(bAccount);

    }
}

测试代码

package com.fs.service.impl;

import com.fs.config.SpringConfig;
import com.fs.pojo.Account;
import com.fs.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AccountServiceImplTestXML {

    @Autowired
    private AccountService accountService;

    //测试查询所有方法
    @Test
    public void findAll() {
        List<Account> all = accountService.findAll();
        System.out.println(all);
    }

    //测试转账方法
    @Test
    public void transferMoneyAtoB() {
        //测试转账方法
        accountService.transferMoneyAtoB("小付","小花",100);
    }


}
transferMoneyAtoB()方法测试运行后数据库中结果

业务层转账方法正常运行成功后数据表数据

由于我们测试代码中是小付向小花转账100元,代码执行成功后应该小付900,小花1100
在这里插入图片描述
业务层转账方法我们给制作一个异常1/0 的/ by zero异常,
运存测试转账方法控制台输出
在这里插入图片描述
数据库中表的数据
小付原本900,小花1100,我们进行了转账业务,但是制作了异常,事务会进行回滚,所以金额不会发生变化

在这里插入图片描述

事务传播行为

在这里插入图片描述

Spring中的7个事务传播行为:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值