Spring12_Spring中的事务控制

2020-06-07 16:06:34来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Spring12_Spring中的事务控制

本教程源码请访问:tutorial_demo

一、概述

之前我们学习了AOP,然后通过AOP对我们的Apache Commons DbUtils实现单表的CRUD操作的代码添加了事务。Spring有其自己的事务控制的机制,我们完全可以在项目中使用Spring自己的事务控制机制。

JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。

二、环境准备

我们之前学习了JdbcTemplate,我们的环境Dao层使用JdbcTemplate,后面三个部分的代码,都在环境准备代码基础之上进行。

2.1、建库建表

DROP DATABASE IF EXISTS springlearn;
CREATE DATABASE springlearn;
USE springlearn;


DROP TABLE IF EXISTS account;
CREATE TABLE account (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(40) DEFAULT NULL,
  money float DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;

INSERT INTO account VALUES ('1', 'aaa', '1000');
INSERT INTO account VALUES ('2', 'bbb', '1000');
INSERT INTO account VALUES ('3', 'ccc', '1000');
INSERT INTO account VALUES ('5', 'cc', '10000');
INSERT INTO account VALUES ('6', 'abc', '10000');
INSERT INTO account VALUES ('7', 'abc', '10000');

2.2、添加Account实体类

package org.codeaction.bean;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2.3、添加Dao接口

package org.codeaction.dao;

import org.codeaction.bean.Account;

import java.util.List;

public interface IAccountDao {
    Integer add(Account account);
    Integer delete(Integer id);
    Integer update(Account account);
    List<Account> findAll();
    Account findById(Integer id);
    List<Account> findByName(String name);
    Long count();
}

2.4、添加Dao接口实现类

package org.codeaction.dao.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate template;

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }

    @Override
    public Integer add(Account account) {
        Object[] args = {account.getName(), account.getMoney()};
        return template.update("insert into account(name, money) values(?, ?)", args);
    }

    @Override
    public Integer delete(Integer id) {
        return template.update("delete from account where id=?", id);
    }

    @Override
    public Integer update(Account account) {
        Object[] args = {account.getName(), account.getMoney(), account.getId()};
        return template.update("update account set name=?, money=? where id=?", args);
    }

    @Override
    public List<Account> findAll() {
        return template.query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
    }

    @Override
    public Account findById(Integer id) {
        List<Account> list = template.query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), id);
        return list.size() != 0 ? list.get(0) : null;
    }

    @Override
    public List<Account> findByName(String name) {
        return template.query("select * from account where name like ?",
                new BeanPropertyRowMapper<Account>(Account.class), name);
    }

    @Override
    public Long count() {
        return template.queryForObject("select count(*) from account", Long.class);
    }
}

2.5、添加Service接口

package org.codeaction.service;

public interface IAccountService {
    void trans(Integer srcId, Integer dstId, Float money);
}

这里只有一个转账操作,也是这个教程的关键。

2.6、添加Service接口实现类

package org.codeaction.service.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

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

    @Override
    public void trans(Integer srcId, Integer dstId, Float money) {
        Account src = accountDao.findById(srcId);
        Account dst = accountDao.findById(dstId);

        if(src == null) {
            throw new RuntimeException("转出用户不存在");
        }

        if(dst == null) {
            throw new RuntimeException("转入用户不存在");
        }

        if(src.getMoney() < money) {
            throw new RuntimeException("转出账户余额不足");
        }

        src.setMoney(src.getMoney() - money);
        dst.setMoney(dst.getMoney() + money);

        accountDao.update(src);

        //int x = 1/0;

        accountDao.update(dst);
    }
}

2.7、添加Spring配置文件beans.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置AccountServiceImpl -->
    <bean id="accountService" class="org.codeaction.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置AccountDaoImpl -->
    <bean id="accountDao" class="org.codeaction.dao.impl.AccountDaoImpl">
        <!-- 注入jdbcTemplate -->
        <property name="template" ref="template"></property>
    </bean>

    <!-- 配置JdbcTemplate -->
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 注入数据源属性 -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

2.8、添加测试类

package org.codeaction.test;

import org.codeaction.service.IAccountService;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class MyTest {
    @Autowired
    private IAccountService accountService;

    @Test
    public void testTrans() {
        accountService.trans(1, 2, 100F);
    }
}

运行测试方法,能够转账成功。如果在AccountServiceImpl的trans中添加int i = 1/0;,转账失败,但是没有回滚,我们在下面的代码中添加事务控制。

三、基于XML的声明式事务控制

基于XML的声明式事务控制在上一节“环境准备”的基础上进行。

3.1、修改Spring配置文件beans.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 配置AccountServiceImpl -->
    <bean id="accountService" class="org.codeaction.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置AccountDaoImpl -->
    <bean id="accountDao" class="org.codeaction.dao.impl.AccountDaoImpl">
        <!-- 注入jdbcTemplate -->
        <property name="template" ref="template"></property>
    </bean>

    <!-- 配置JdbcTemplate -->
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 注入数据源属性 -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事务的通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的属性 -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="pt" expression="execution(* org.codeaction.service.impl.*.*(..))"></aop:pointcut>
        <!-- 建立切入点表达式和事务通知的对应关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>
</beans>

Spring中基于XML的声明式事务控制配置步骤:

  1. 配置事务管理器;
  2. 配置事务的通知;
  3. 配置AOP中通用切入点表达式;
  4. 建立切入点表达式和事务通知的对应关系;
  5. 配置事务的属性。

事务的属性如下:

  1. isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别;
  2. propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS;
  3. read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写;
  4. timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位;
  5. rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚;
  6. no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。

3.2、测试

运行转账的测试方法,能够正常转账,出现异常时,能够正常回滚。

四、基于XML和注解的声明式事务控制

4.1、修改Spring配置文件beans.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置Spring创建容器时要扫描的包 -->
    <context:component-scan base-package="org.codeaction"></context:component-scan>

    <!-- 配置JdbcTemplate -->
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 注入数据源属性 -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启Spring对注解事务的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

4.2、修改Dao接口的实现类

package org.codeaction.dao.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private JdbcTemplate template;

    @Override
    public Integer add(Account account) {
        Object[] args = {account.getName(), account.getMoney()};
        return template.update("insert into account(name, money) values(?, ?)", args);
    }

    @Override
    public Integer delete(Integer id) {
        return template.update("delete from account where id=?", id);
    }

    @Override
    public Integer update(Account account) {
        Object[] args = {account.getName(), account.getMoney(), account.getId()};
        return template.update("update account set name=?, money=? where id=?", args);
    }

    @Override
    public List<Account> findAll() {
        return template.query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
    }

    @Override
    public Account findById(Integer id) {
        List<Account> list = template.query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), id);
        return list.size() != 0 ? list.get(0) : null;
    }

    @Override
    public List<Account> findByName(String name) {
        return template.query("select * from account where name like ?",
                new BeanPropertyRowMapper<Account>(Account.class), name);
    }

    @Override
    public Long count() {
        return template.queryForObject("select count(*) from account", Long.class);
    }
}

4.3、修改Service接口的实现类

package org.codeaction.service.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void trans(Integer srcId, Integer dstId, Float money) {
        Account src = accountDao.findById(srcId);
        Account dst = accountDao.findById(dstId);

        if(src == null) {
            throw new RuntimeException("转出用户不存在");
        }

        if(dst == null) {
            throw new RuntimeException("转入用户不存在");
        }

        if(src.getMoney() < money) {
            throw new RuntimeException("转出账户余额不足");
        }

        src.setMoney(src.getMoney() - money);
        dst.setMoney(dst.getMoney() + money);

        accountDao.update(src);

        //int x = 1/0;

        accountDao.update(dst);
    }
}

4.4、测试

运行转账的测试方法,能够正常转账,出现异常时,能够正常回滚。

五、基于纯注解的声明式事务控制

纯注解配置就用不到XML配置文件了,我们在上一节的基础上进行配置,删除beans.xml。

5.1、修改Dao接口的实现类

package org.codeaction.dao.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private JdbcTemplate template;

    @Override
    public Integer add(Account account) {
        Object[] args = {account.getName(), account.getMoney()};
        return template.update("insert into account(name, money) values(?, ?)", args);
    }

    @Override
    public Integer delete(Integer id) {
        return template.update("delete from account where id=?", id);
    }

    @Override
    public Integer update(Account account) {
        Object[] args = {account.getName(), account.getMoney(), account.getId()};
        return template.update("update account set name=?, money=? where id=?", args);
    }

    @Override
    public List<Account> findAll() {
        return template.query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
    }

    @Override
    public Account findById(Integer id) {
        List<Account> list = template.query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), id);
        return list.size() != 0 ? list.get(0) : null;
    }

    @Override
    public List<Account> findByName(String name) {
        return template.query("select * from account where name like ?",
                new BeanPropertyRowMapper<Account>(Account.class), name);
    }

    @Override
    public Long count() {
        return template.queryForObject("select count(*) from account", Long.class);
    }
}

5.2、修改Service接口的实现类

package org.codeaction.service.impl;

import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void trans(Integer srcId, Integer dstId, Float money) {
        Account src = accountDao.findById(srcId);
        Account dst = accountDao.findById(dstId);

        if(src == null) {
            throw new RuntimeException("转出用户不存在");
        }

        if(dst == null) {
            throw new RuntimeException("转入用户不存在");
        }

        if(src.getMoney() < money) {
            throw new RuntimeException("转出账户余额不足");
        }

        src.setMoney(src.getMoney() - money);
        dst.setMoney(dst.getMoney() + money);

        accountDao.update(src);

        int x = 1/0;

        accountDao.update(dst);
    }
}

5.3、添加配置类及JDBC配置文件

5.3.1、添加JDBC配置文件

在resource目录下,文件名:jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springlearn
jdbc.username=root
jdbc.password=123456

5.3.2、添加JDBC配置类

package org.codeaction.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

public class JdbcConfig {
    @Value("${jdbc.driverClass}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "dataSource")
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

5.3.3、添加事务配置类

package org.codeaction.config;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

public class TransactionConfig {

    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

这个配置类用来创建事务管理器。

5.3.4、添加主配置类

package org.codeaction.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = "org.codeaction")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

这个配置类做了如下几件事:

  1. 声明自己是一个配置类;
  2. 开启包扫描,并配置要扫描的包;
  3. 引入JDBC配置文件;
  4. 引入另外的两个配置类;
  5. 开启Spring对注解事务的支持。

5.4、测试

运行转账的测试方法,能够正常转账,出现异常时,能够正常回滚。


原文链接:https://www.cnblogs.com/codeaction/p/13062248.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:深入理解:设计模式中的七大设计原则

下一篇:Java跨平台原理(字节码文件、虚拟机) 以及Java安全性