Spring的事物管理

一、事务

事务的个性(ACID)

原子性: 一个事务是最小的执行单元,不可以分割

一致性: 事务指定的前后,数据要保持一致.

持久性: 事务一旦提交或回滚,在数据库中持久的改变.

隔离性: 隔离性用来保证多个用户来操作数据库的同一份数据,不会受到相关干扰的特性.

并发操作数据库会出现的问题:

脏读: 一个事务读到了另一个事务的还没有提交数据.

不可重复读: 一个事务中多次读到的数据不一致.一个事务读到了另一个事务修改后的数据.

幻读(虚读): 一个事务读到了insert的数据.

隔离级别 出现的问题
读未提交 read uncommited 都会出现
读以提交 read committed 不会出现脏读, 但是会出现不可重复读和幻读 (oracle默认隔离级别)
可重复读 repeatable read 不会出现脏读 不可重复读 , 但会出现幻读(mysql的默认隔离级别)
串行化 serializable 以上问题都不会出现.(不支持并发)

二、spring的事务管理

1、PlatformTransactionManager 平台事务管理器

会使用它的子类: DataSourceTransactionManager

注意事项: 如果要用平台事务管理器, 该管理器中必须有连接池对象

里面的常用方法:

a) * commit 进行事务提交

b) * rollback 进行事务回滚

c) * TransactionStatus getTransaction(TransactionDefinition definition)

2、TransactionDefinition 事务定义信息(隔离、传播、超时、只读)

该接口中定义类很多常量:用户我们设置不同的隔离级别 传播行为, 超时时间,是否为只读事务

1) ISOLATION_xxx 设置事务的隔离级别

2) PROPAGATION_xxx 事务传播行为

3) TIMEOUT_DEFAULT 默认超时时间

4) isReadOnly() 事务是否只读

传播行为图解:

三、spring基于xml的事务管理

1).目标搭建一个转账的环境(没有事务)

1.准备环境: 数据库的搭建

CREATE TABLE `account` (
  `id` INT(8) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(64) DEFAULT NULL,
  `money` DOUBLE DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO account VALUES(NULL,'aaa',1000);
INSERT INTO account VALUES(NULL,'bbb',1000);

2.导入jar

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

    <!--
       spring JdbcTemplate
       1)mysql
       2)spring-context
       3)spring-jdbc
       4)spring-test
       5)junit
       6)lombok
       7)管理事务 aop
   -->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.2</version>
        </dependency>
    </dependencies>
</project>

2.编写代码

AccountDao

package com.itheima.dao;

public interface AccountDao {

    //转入
    public void transferIn(String inName ,double money);


    //转出
    public void transferOut(String outName ,double money);

}

AccountDaoImpl

package com.itheima.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 使用JdbcTemplate 注入进来,完成数据的修改
 */
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void transferIn(String inName, double money) {
        jdbcTemplate.update("update account set money = money + ? where name = ?", money,inName);
    }

    public void transferOut(String outName, double money) {
        jdbcTemplate.update("update account set money = money - ? where name = ?", money,outName);
    }
}

AccountService

public interface AccountService {

    public void transfer(String inName, String outName,double money);
}

AccountServiceImpl

package com.itheima.service;

import com.itheima.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void transfer(String inName, String outName, double money) {
        accountDao.transferIn(inName,money);

        //模拟异常
        int i = 1/0;

        accountDao.transferOut(outName,money);
    }
}

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day25?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

log4j.properties

# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...

#以下配置输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#输出的格式
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nlog4j.rootLogger=INFO, stdout
# Console output...

#以下配置输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#输出的格式
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

bean2.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <!--0.引入外部数据源-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--1.创建连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <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>

    <!--2.创建JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--3.创建AccountDao-->
    <bean id="accountDao" class="com.itheima.dao.AccountDaoImpl"></bean>

    <!--4.创建AccountService-->
    <bean id="accountService" class="com.itheima.service.AccountServiceImpl"></bean>

</beans>

测试Dao

package com.itheima.dao;

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 static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean2.xml")
public class AccountDaoImplTest {

    @Autowired
    private AccountDao accountDao;

    @Test
    public void transferIn() {
        accountDao.transferIn("aaa",200);
    }

    @Test
    public void transferOut() {
        accountDao.transferOut("bbb",200);
    }
}

测试Service

package com.itheima.service;

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 static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean2.xml")
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void transfer() {
        accountService.transfer("aaa","bbb",500);
    }
}

2).给该环境添加spring的事务管理 

spring进行事务管理,使用平台事务管理器---DataSourceTransactionManager ,必须提供dataSource

实现的步骤:

1.在bean.xml中创建DataSourceTransactionManager 注入dataSource

2.做一个通知(增强) 配置指定的方法,给指定的方法上配置 事务的隔离级别 事务的传播行为 是否只读,超时

3.配置一个aop

配置切点(要哪些方法进行事务的控制)

通知和切面的组合.(使用通知在增强切点)

以上三个配置完毕, 源代码不用修改直接添加事务的控制.

事务的控制使用xml方式在bean.xml中完成以下配置即可.

......上面的省略 
<!--1.声明平台事务管理器 DataSourceTransactionManager (传递dataSource)-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--配置一个通知(增强)-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--配置哪些方法需要被增强, 设置隔离级别  传播行为 是否只读  超时时间
               name="transfer*"  设置要事务管理进行增强的方法
               isolation="REPEATABLE_READ"  设置隔离级别
               propagation="REQUIRED" 设置传播行为
               read-only="false" 设置是否为只读事务
               timeout="-1"  超时时间为-1 不超时
            -->
            <tx:method name="transfer*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" timeout="-1" />
        </tx:attributes>
    </tx:advice>

    <!--配置aop-->
    <aop:config>
        <!--配置切点-->
        <aop:pointcut id="pointcut" expression="execution(* com.itheima.service..transfer*(..))"/>
        <!--切点和增强的组合-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

四、spring基于注解的事务管理

1.重写编写一个配置文件,配置文件中的内容是包扫描

DriverManagerDataSource JdbcTemplate DataSourceTransactionManager 这些类还需要在xml中进行配置.

   注解方式的事物管理“”

2.给所有Service和dao上的类上添加对应的注解.

3.bean.xml中补充一个注解驱动 (注解事务的管理)

4.谁需要管理事务给谁添加一个@Transactional 注解即可.

bean3.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 http://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 http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--0.引入外部数据源-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--1.创建连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <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>

    <!--2.创建JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--添加事务的控制-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--添加包扫描-->
    <context:component-scan base-package="com.itheima"/>

    <!--添加注解驱动(挂在平台事务管理器)-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

给service的实现类上添加@Transactional注解,既可以有事务的控制.

package com.itheima.service;

import com.itheima.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
//@Transactional 注解可以对该类上的所有方法都添加事务的控制 (该注解中有默认值的设置,设置了隔离级别,传播行为,超时时间,是否只读等信息)
//@Transactional(isolation = Isolation.REPEATABLE_READ ,propagation = Propagation.REQUIRED)
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void transfer(String inName, String outName, double money) {
        accountDao.transferIn(inName,money);

        //模拟异常
        int i = 1/0;

        accountDao.transferOut(outName,money);
    }

    public void find(){}
}
原文地址:https://www.cnblogs.com/haojia/p/12386231.html