Spring 事务管理

2019-11-04  本文已影响0人  weihy

本文摘抄至实验楼教程:https://www.shiyanlou.com/courses/578/learning/?id=1942

本文来学习Spring的事务管理,事务在日常开发中非常重要,它可以多数据库的一些异常进行回滚,以确保数据的一致性。

事务的四个特性:



Spring 中的事务管理有两种方式:

  1. 编程式事务管理:
    所谓编程式事务管理,是通过编程方式实现事务,允许用户在代码中精确定义事务的边界;管理使用 TransactionTemplate或者 PlatformTransactionManager。对于编程式事务管理,Spring推荐使用TransactionTemplate
  2. 声明式事务管理:
    管理建立在AOP之上。其本质是对方法的前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务的最大有点就是不需要通过编程的方法管理,这样就不需要在业务逻辑代码中掺杂事务管理的代码,只需要在配置文件中做相关的事务规则声明(或者基于@Transactional注解的方式)。
1、编程式事务管理

本文使用到Msql数据库,使用Sqlyog客户端连接数据库。
新建一个数据库命名为transaction,创建账户表并插入两条记录:

CREATE DATABASE `transaction` CHARACTER SET utf8; 

USE `transaction`;

CREATE TABLE `account`(`id` INT PRIMARY KEY AUTO_INCREMENT,
`username` VARCHAR(20),
`money` INT) ;

INSERT INTO `account` VALUES(1,"张三",30000),(2,"李四",50000);

执行结果:


image.png



新建一个maven工程springTransaction,相应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.shiyanlou.tx</groupId>
  <artifactId>springTransaction</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springTransaction</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

首先创建包com.shiyanlou.tx.dao,创建接口AccountDao.java,代码如下:

package com.shiyanlou.tx.dao;

/**
 * Created by Administrator on 2019/11/3.
 */
public interface AccountDao {

    /**
     * 汇款
     * @param outer 汇款人
     * @param money 汇款金额
     */
    public void out(String outer,int money);

    /**
     * 收款
     * @param inner 收款人
     * @param money 收款金额
     */
    public void in(String inner,int money);
}

再在这个包下创建实现类AcountDaoImpl.java,如下:

package com.shiyanlou.tx.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * Created by Administrator on 2019/11/3.
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    /**
     * 根据用户名减少账户金额
     * @param outer 汇款人
     * @param money 汇款金额
     */
    @Override
    public void out(String outer, int money) {
        this.getJdbcTemplate().update("update account set money = money - ? where username = ?",money,outer);
    }

    /**
     * 根据用户名增加账户金额
     * @param inner 收款人
     * @param money 收款金额
     */
    @Override
    public void in(String inner, int money) {
        this.getJdbcTemplate().update("update account set money = money + ? where username = ?",money,inner);
    }
}

创建包com.shiyanlou.tx.service,创建接口AccountService.java,如下:

package com.shiyanlou.tx.service;

/**
 * Created by Administrator on 2019/11/4.
 */
public interface AccountService {

    /**
     * 转账
     * @param outer 汇款人
     * @param inner 收款人
     * @param money 交易金额
     */
    public void transfer(String outer, String inner, int money);
}

再在这个包下创建,实现类AccountServiceImpl.java,如下:

package com.shiyanlou.tx.service;


import com.shiyanlou.tx.dao.AccountDao;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Created by Administrator on 2019/11/4.
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    public AccountDao getAccountDao() {
        return accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public TransactionTemplate getTransactionTemplate() {
        return transactionTemplate;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public void transfer(final String outer, final String inner, final int money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult(){

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountDao.out(outer,money);
                int i = 1/0;
                accountDao.in(inner,money);
            }
        });
    }
}

src/main下创建resources文件夹,创建Spring配置文件SpringBeans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:23306/transaction"/>
        <property name="username" value="root"/>
        <property name="password" value="wei085"/>
    </bean>

    <!--创建模板-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="txManager"/>
    </bean>
    <!--配置事务管理器,管理器需要事务,事务从connection获取,connection从连接池dataSource获取-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="accountDao" class="com.shiyanlou.tx.dao.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="accountService" class="com.shiyanlou.tx.service.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="transactionTemplate" ref="transactionTemplate"/>
    </bean>
</beans>

最后在包路径com.shiyanlou.tx下创建App.java,如下:

package com.shiyanlou.tx;

import com.shiyanlou.tx.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{

    private static ApplicationContext context;

    public static void main( String[] args )
    {
        context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        AccountService account = (AccountService) context.getBean("accountService");
//        张三向李四转账10000
        account.transfer("张三","李四",10000);

    }
}

运行App.java,抛出异常:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.shiyanlou.tx.service.AccountServiceImpl.transfer(AccountServiceImpl.java:39)
    at com.shiyanlou.tx.App.main(App.java:22)

发现数据库的数据没有改变,因为我们加入了事务管理,程序异常,数据会回滚。


image.png

现在我们修改AccountServiceImpl.java的代码,将事务管理去掉,如下:

package com.shiyanlou.tx.service;


import com.shiyanlou.tx.dao.AccountDao;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Created by Administrator on 2019/11/4.
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public AccountDao getAccountDao() {
        return accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(final String outer, final String inner, final int money) {
        accountDao.out(outer,money);
        int i = 1/0;
        accountDao.in(inner,money);
    }
}

再修改SpringBeans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:23306/transaction"/>
        <property name="username" value="root"/>
        <property name="password" value="wei085"/>
    </bean>

    <bean id="accountDao" class="com.shiyanlou.tx.dao.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="accountService" class="com.shiyanlou.tx.service.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

再次运行App.java,同样抛出异常,但是没有加入事务管理,所以数据库没有回滚,如下:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.shiyanlou.tx.service.AccountServiceImpl.transfer(AccountServiceImpl.java:39)
    at com.shiyanlou.tx.App.main(App.java:22)
image.png
2、声明式事务管理

首先修改SpringBeans.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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:23306/transaction"/>
        <property name="username" value="root"/>
        <property name="password" value="wei085"/>
    </bean>

    <!--1、配置事务管理器,管理器需要事务,事务从connection获取,connection从连接池dataSource获取-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--2、将管理器交给Spring
    * transaction-manager:配置事务管理器
    * proxy-target-class: true 底层强制使用cglib代理-->
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>

    <bean id="accountDao" class="com.shiyanlou.tx.dao.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="accountService" class="com.shiyanlou.tx.service.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

然后修改AccountServiceImpl.java中的代码:

package com.shiyanlou.tx.service;


import com.shiyanlou.tx.dao.AccountDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by Administrator on 2019/11/4.
 */

@Transactional(propagation= Propagation.REQUIRED , isolation = Isolation.DEFAULT)
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource(name="accountDao")
    private AccountDao accountDao;

    public AccountDao getAccountDao() {
        return accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(final String outer, final String inner, final int money) {
                accountDao.out(outer,money);
//                int i = 1/0;
                accountDao.in(inner,money);
    }
}

现将int i = 1/0;注释,验证程序的正确性,运行,结果如下:

image.png

数据发生了变化,说明去掉异常的代码是正确的;再把上面的注释放开,再运行,抛出如下:

Exception in thread "main" java.lang.ArithmeticException: / by zero

查看数据库,由于程序异常,数据库回滚,数据未更新:


image.png
上一篇下一篇

猜你喜欢

热点阅读