当前位置:   article > 正文

Spring整合Mybatis(事务篇)_mybatis 事务

mybatis 事务

Spring整合Mybatis(事务篇)

一、XML版

TxXMLSpringMixMybatis项目

准备工作

Accout表sql

/*
 Navicat Premium Data Transfer

 Source Server         : mysql80
 Source Server Type    : MySQL
 Source Server Version : 80029
 Source Host           : localhost:3306
 Source Schema         : spring_mybatis

 Target Server Type    : MySQL
 Target Server Version : 80029
 File Encoding         : 65001

 Date: 12/10/2022 19:15:03
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `balance` decimal(20, 2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '老王', 10000.00);
INSERT INTO `account` VALUES (2, '隔壁的', 0.00);

SET FOREIGN_KEY_CHECKS = 1;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

主要代码

在这里插入图片描述

全部代码

pom.xml

<?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.bjpowernode</groupId>
    <artifactId>TxXMLSpringMixMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

        <!--log-->
        <!-- 日志相关jar包  开始 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
        <!--tool-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104

com.bjpowernode.domain
Account.java

package com.bjpowernode.domain;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Account {
    private Long id;
    private String name;
    private BigDecimal balance;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

com.bjpowernode.mapper
AccountMapper.java

package com.bjpowernode.mapper;

import org.apache.ibatis.annotations.Param;

import java.math.BigDecimal;

public interface AccountMapper {
    // 转出去
    public void transOut(@Param("outName") String outname, @Param("money") BigDecimal money) ;

    // 转进来
    public void transIn(@Param("inName") String inname, @Param("money") BigDecimal money);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

com.bjpowernode.service
AccountService.java

package com.bjpowernode.service;

import java.math.BigDecimal;

public interface AccountService {
    void trans(String outname, String inname, BigDecimal money);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

com.bjpowernode.service.impl

package com.bjpowernode.service.impl;

import com.bjpowernode.mapper.AccountMapper;
import com.bjpowernode.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void trans(String outname, String inname, BigDecimal money) {
        //前置增强
        accountMapper.transOut(outname,money);
        int i = 1/0;
        accountMapper.transIn(inname,money);
        //后置增强
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

resources资源文件夹下
com.bjpowernode.mapper
AccountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.AccountMapper">


    <update id="transOut">
        update account set balance = balance - #{money} where name = #{outName}
    </update>

    <update id="transIn">
        update account set balance = balance + #{money} where name = #{inName}
    </update>
</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

resources
db.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///spring_mybatis?useSSL=false
username=root
password=root
  • 1
  • 2
  • 3
  • 4

resources
log4j.properties

log4j.rootLogger=ERROR, stdout

log4j.logger.com.bjpowernode.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <!-- 设置为 false 表示每个延迟加载属性会按需加载 -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!--是否开启懒加载 总开关 延迟加载的全局开关-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--指定对象的哪些方法触发一次延迟加载-->
        <setting name="lazyLoadTriggerMethods" value="clone"/>
    </settings>


</configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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">

    <!--关联数据库的配置信息-->
    <context:property-placeholder location="classpath:db.properties"
                                  system-properties-mode="NEVER"/>

    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--sqlsession-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.bjpowernode.domain"/>
        <!-- pageHelper插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            helperDialect=mysql
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--mapper扫描器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"/>
    </bean>

    <!--xml-->
    <bean class="com.bjpowernode.service.impl.AccountServiceImpl"/>


    <!--使用aop 对 方法 进行 事务对增强-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource"  ref="dataSource"/>
    </bean>

    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="select*" read-only="true"/>
            <tx:method name="list*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <!--
            read-only 只读
            isolation 数据库对隔离级别 MySql 默认的 隔离级别(3、可重复读(Repeated Read):可重复读) 一般不需要该
            propagation 传播行为  REQUIRED 默认的
            -->
            <tx:method name="*"   isolation="DEFAULT" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <!--切入点-->
        <aop:pointcut id="point"
                      expression="execution(* com.bjpowernode.service.impl.*Impl.*(..))"/>

        <!--织入-->
        <aop:advisor advice-ref="advice" pointcut-ref="point"/>
    </aop:config>

</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

测试类

package com.bjpowernode.test;

import com.bjpowernode.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.math.BigDecimal;

public class TxXMLSpringMixMybatis {

    // 需求:老王给隔壁的转1000元
    @Test
    public void testTransaction(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = applicationContext.getBean(AccountService.class);
        accountService.trans("老王","隔壁的",new BigDecimal("1000"));
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

二、注解版

在XML版的基础上,先贴修改部分的代码,再贴全部代码
applicationContext.xml配置文件

主要代码

在这里插入图片描述
service层的实现类AccountServiceImpl.java修改的代码
在这里插入图片描述

全部代码

pom.xml

<?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.bjpowernode</groupId>
    <artifactId>TxAnnoSpringMixMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

        <!--log-->
        <!-- 日志相关jar包  开始 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
        <!--tool-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104

com.bjpowernode.domain
Account.java

package com.bjpowernode.domain;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Account {
    private Long id;
    private String name;
    private BigDecimal balance;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

com.bjpowernode.mapper
AccountMapper.java

package com.bjpowernode.mapper;

import org.apache.ibatis.annotations.Param;

import java.math.BigDecimal;

public interface AccountMapper {
    // 转出去
    public void transOut(@Param("outName") String outname, @Param("money") BigDecimal money) ;

    // 转进来
    public void transIn(@Param("inName") String inname, @Param("money") BigDecimal money);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

com.bjpowernode.service
AccountService.java

package com.bjpowernode.service;

import java.math.BigDecimal;

public interface AccountService {
    void trans(String outname, String inname, BigDecimal money);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

com.bjpowernode.service.impl
AccountServiceImpl.java

package com.bjpowernode.service.impl;

import com.bjpowernode.mapper.AccountMapper;
import com.bjpowernode.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional(isolation = Isolation.DEFAULT,readOnly=true) // 针对类中所有方法都添加事务
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional // 只针对当前方法有效
    @Override
    public void trans(String outname, String inname, BigDecimal money) {
        //前置增强
        accountMapper.transOut(outname,money);
        int i = 1/0;
        accountMapper.transIn(inname,money);
        //后置增强
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

resources
com.bjpowernode.mapper
AccountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.AccountMapper">


    <update id="transOut">
        update account set balance = balance - #{money} where name = #{outName}
    </update>

    <update id="transIn">
        update account set balance = balance + #{money} where name = #{inName}
    </update>
</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

resources
db.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///spring_mybatis?useSSL=false
username=root
password=root
  • 1
  • 2
  • 3
  • 4

log4j.properties

log4j.rootLogger=ERROR, stdout

log4j.logger.com.bjpowernode.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


<!--    <settings>-->
<!--        <setting name="logImpl" value="LOG4J"/>-->
<!--        &lt;!&ndash; 设置为 false 表示每个延迟加载属性会按需加载 &ndash;&gt;-->
<!--        <setting name="aggressiveLazyLoading" value="false" />-->
<!--        &lt;!&ndash;是否开启懒加载 总开关 延迟加载的全局开关&ndash;&gt;-->
<!--        <setting name="lazyLoadingEnabled" value="true"/>-->
<!--        &lt;!&ndash;指定对象的哪些方法触发一次延迟加载&ndash;&gt;-->
<!--        <setting name="lazyLoadTriggerMethods" value="clone"/>-->
<!--    </settings>-->


</configuration>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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">

    <!--关联数据库的配置信息-->
    <context:property-placeholder location="classpath:db.properties"
                                  system-properties-mode="NEVER"/>

    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--sqlsession-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--关联mybatis的主配置文件-->
<!--        <property name="configLocation" value="classpath:mybatis-config.xml"/>-->
        <!--关联配置类 和 configLocation 只能选择其一-->
        <property name="configuration" ref="config"/>

        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.bjpowernode.domain"/>
        <!-- pageHelper插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            helperDialect=mysql
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--Log4j-->
    <bean id="config" class="org.apache.ibatis.session.Configuration">
        <!-- 指定日志工具 -->
        <property name="logImpl"  value="org.apache.ibatis.logging.log4j.Log4jImpl" />

        <!-- 设置为 false 表示每个延迟加载属性会按需加载 -->
        <property name="aggressiveLazyLoading" value="false" />
        <!--是否开启懒加载 总开关 延迟加载的全局开关-->
        <property name="lazyLoadingEnabled" value="true"/>
        <!--指定对象的哪些方法触发一次延迟加载-->
        <property name="lazyLoadTriggerMethods" value="clone"/>
    </bean>

    <!--mapper扫描器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"/>
    </bean>



    <!--使用aop 对 方法 进行 事务对增强-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource"  ref="dataSource"/>
    </bean>
    <!--自动开启事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>


    <!--ioc扫描器-->
    <context:component-scan base-package="com.bjpowernode.service.impl"/>


</beans>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

测试类

  // 需求:老王给隔壁的转1000元
    @Test
    public void testTransaction(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = applicationContext.getBean(AccountService.class);
        accountService.trans("老王","隔壁的",new BigDecimal("1000"));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

三、事务的传播性

在注解版的基础之上新增以下代码
AccountServiceImpl.java

package com.bjpowernode.service.impl;

import com.bjpowernode.mapper.AccountMapper;
import com.bjpowernode.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;
    
    @Override
    public void trans(String outname, String inname, BigDecimal money) {
        //前置增强
        accountMapper.transOut(outname,money);
        int i = 1/0;
        accountMapper.transIn(inname,money);
        //后置增强
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

UserService

package com.bjpowernode.service;

import java.math.BigDecimal;

public interface UserService {

    void handleTrans(String outname, String inname, BigDecimal money);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

UserServiceImpl.java

package com.bjpowernode.service.impl;
import com.bjpowernode.service.AccountService;
import com.bjpowernode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AccountService accountService;


    @Override
    public void handleTrans(String outname, String inname, BigDecimal money) {
        accountService.trans(outname,inname,money);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

测试类

 // 需求:老王给隔壁的转1000元
    @Test
    public void testTransaction(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = applicationContext.getBean(UserService.class);
        userService.handleTrans("老王","隔壁的",new BigDecimal("1000"));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在这里插入图片描述

在这里插入图片描述

REQUIRED

必须的,默认值,表示当前若存在事务则使用当前事务,若不存在则创建一个新的事务
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
等价于
在这里插入图片描述
等价于外层没有事务、内层有事务
等价于下面2张图
在这里插入图片描述
在这里插入图片描述
结果和之前一样
在这里插入图片描述

SUPPORTS

支持的,表示当前若存在事务则在当前事务中执行,若不存在则在非事务中执行

当前有事务
在这里插入图片描述
在这里插入图片描述
结果和之前一样
在这里插入图片描述
当前没有事务
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

MANDATORY

强制性,表示必须在事务中执行,若当前没有事务则抛出异常
在这里插入图片描述
在这里插入图片描述
抛出异常
org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation ‘mandatory’
在这里插入图片描述

NEVER

绝不,表示一定不在事务中执行,若当前存在事务则报错

当前有事务
在这里插入图片描述

在这里插入图片描述
抛出异常
org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation ‘never’
在这里插入图片描述

NESTED

嵌套的,若当前存在事务,则创建一个子事务,嵌套在当前事务中,
注意,外层事务出现异常会回滚子事务,子事务出现异常,不影响外层事务

外层事务出现异常
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
子事务出现异常,不影响外层事务
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/707727
推荐阅读
相关标签
  

闽ICP备14008679号