Spring(八)Spring中的事务 && 声明式事务 && 编程式事务

Spring中的事务

一、前言

第一:JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。
第二:spring框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在spring-tx-5.0.2.RELEASE.jar 中。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>

第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。

二、Spring中事务控制的API介绍

1. PlatformTransactionManager

这个接口是Spring的事务管理器,它里面提供了我们常用的操作事务的方法,包含有3个具体的操作:

  • 获取事务状态信息:TransactionStatus getTransaction(TransactionDefinition definition)
  • 提交事务:void commit(TransactionStatus var1) throws TransactionException
  • 回滚事务:void rollback(TransactionStatus var1) throws TransactionException

我们在开发的时候,都是使用它的具体实现类:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring JDBC 或 iBatis 进行持久化数据时使用
  • org.springframework.orm.hibernate5.HibernateTransactionManager 使用 Hibernate 版本进行持久化数据时使用

2. TransactionDefinition

它是事务的定义信息对象,里面有如下的方法:

  • 获取事务传播行为:int getPropagationBehavior()
  • 获取事务隔离级别:int getIsolationLevel()
  • 获取事务超时时间:int getTimeout()
  • 获取事务是否只读:boolean isReadOnly()
  • 获取事务对象名称:String getName()
① 事务的隔离级别

事务的隔离级别反映的事务提交并发访问时的处理态度:
ISOLATION_DEFAULT:默认级别,归属于下面的某一种
ISOLATION_READ_UNCOMMITTED:可以读取未提交数据
ISOLATION_READ_COMMITTED:只能读取已提交的数据,解决脏读问题(Oracle默认级别)
ISOLATION_REPEATABLE_READ:是否读取其他事务提交修改后的数据,解决不可重复读的问题(MySQL默认级别)
ISOLATION_SERIALIZABLE:是否读取其他事务提交添加后的数据,解决幻影读问题

② 事务的传播行为

REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选 择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED 类似的操作。

③ 超时时间

默认值为-1,没有超时限制。如果有,以秒为单位进行设置。

④ 是否是只读事务

建议查询时设置为只读。

3. TransactionStatus

  • 获取事务是否为新的事务:boolean isNewTransaction();
  • 获取是否存在存储点:boolean hasSavepoint();
  • 设置事务是否回滚:void setRollbackOnly();
  • 获取事务是否回滚boolean isRollbackOnly();
  • 刷新事务:void flush();
  • 获取事务是否完成:boolean isCompleted();

三、示例代码准备

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.veeja</groupId>
    <artifactId>spring_day04_03</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

Account实体类:

package com.veeja.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 *
 * @Author veeja
 * 2020/5/14 10:22
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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;
    }
}

账户的持久层:

IAccountDao

package com.veeja.dao;

import com.veeja.domain.Account;

/**
 * 账户的持久层接口
 *
 * @Author veeja
 * 2020/5/14 13:06
 */
public interface IAccountDao {
    /**
     * 根据Id查询账户
     *
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 根据名称查询账户
     *
     * @param Name
     * @return
     */
    Account findAccountByName(String Name);


    /**
     * 更新账户信息
     *
     * @param account
     */
    void updateAccount(Account account);
}

AccountDaoImpl

package com.veeja.dao.impl;

import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

/**
 * 账户的持久层实现类
 *
 * @Author veeja
 * 2020/5/14 13:12
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return (accounts.isEmpty() ? null : accounts.get(0));
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name =?",
                new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()) {
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("查询结果不唯一,参数有误!");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",
                account.getName(), account.getMoney(), account.getId());
    }
}

账户的业务层:

IAccountService

package com.veeja.service;

import com.veeja.domain.Account;

/**
 * 账户的业务层接口
 *
 * @Author veeja
 * 2020/5/15 18:03
 */
public interface IAccountService {
    /**
     * 根据id查询账户信息
     *
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 转账操作
     *
     * @param sourceName 转出账户名称
     * @param targetName 转入账户名称
     * @param money      金额
     */
    void transfer(String sourceName, String targetName, Float money);

}

AccountServiceImpl

package com.veeja.service.impl;

import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import com.veeja.service.IAccountService;


/**
 * 账户的业务层实现类
 *
 * @author veeja
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    @Override
    public Account findAccountById(Integer accountId) {

        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {

        /*
         * 2.执行操作
         * 2.1.根据名称查询转出账户
         * 2.2.根据名称查询转入账户
         * 2.3.转出账户减钱
         * 2.4.转入账户加钱
         * 2.5.更新转出账户
         * 2.6.更新转入账户
         */
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDao.updateAccount(source);
        // int i = 1 / 0;
        accountDao.updateAccount(target);

    }
}

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

    <!--配置账户的业务层 accountService-->
    <bean id="accountService" class="com.veeja.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.veeja.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0000"></property>
    </bean>

</beans>

测试类:

package com.veeja.test;

import com.veeja.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;

/**
 * @Author veeja
 * 2020/5/15 18:11
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService accountService;

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

上面的基础代码,是可以实现正常的数据库操作的时候,但是出现异常的时候,却无法回滚,也就是还不支持事务。

四、基于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
        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">

    <!--配置账户的业务层 accountService-->
    <bean id="accountService" class="com.veeja.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.veeja.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0000"></property>
    </bean>

    <!--spring中基于xml的声明式事务控制配置步骤
        1. 配置事务管理器
        2. 配置事务的通知
            此时我们需要导入事务的约束:tx名称空间和约束,同时也需要aop的
            使用tx:advice标签配置事务通知
                属性:
                    id:给事务通知起一个唯一的标识
                    transaction-manager:给事务通知提供一个事务管理器引用
        3. 配置aop中的通用切入点表达式
        4. 建立事务通知和切入点表达式的对应关系
        5. 配置事务的属性
            是在事务的通知tx:advice标签的内部
    -->

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

    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事务的属性
                isolation:用于指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别
                propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询的、方法可以选择SUPPORTS。
                read-only:用于指定事务是否为可读。只有查询方法才能设置为true。默认值为false,表示读写。
                timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
                rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,表示任何异常都回滚。
        -->
        <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="pt1" expression="execution(* com.veeja.service.impl.*.*(..))"/>
        <!--建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

基于注解的方式,我们只要把bean.xml文件稍作改善就能直接使用,其他的文件都不需要改。

五、基于注解的声明式事务配置

1. 导入名称空间

在这里插入图片描述

2. 业务层

添加注解:@Service("accountService")以及@Transactional

@Transactional注解的属性和 xml 中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持 。
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口

/**
 * 账户的业务层实现类
 *
 * @author veeja
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {

        /*
         * 2.执行操作
         * 2.1.根据名称查询转出账户
         * 2.2.根据名称查询转入账户
         * 2.3.转出账户减钱
         * 2.4.转入账户加钱
         * 2.5.更新转出账户
         * 2.6.更新转入账户
         */
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDao.updateAccount(source);
        int i = 1 / 0;
        accountDao.updateAccount(target);

    }
}

3. 持久层

/**
 * 账户的持久层实现类
 *
 * @Author veeja
 * 2020/5/14 13:12
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return (accounts.isEmpty() ? null : accounts.get(0));
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name =?",
                new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()) {
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("查询结果不唯一,参数有误!");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set name=?,money=? where id=?",
                account.getName(), account.getMoney(), account.getId());
    }
}

4. bean.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="com.veeja"></context:component-scan>

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

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0000"></property>
    </bean>

    <!--spring中基于注解的声明式事务控制配置步骤
        1. 配置事务管理器
        2. 开启spring对注解事务的支持
    `   3. 在需要使用事务支持的时候使用@Transactional注解
    -->

    <!--配置事务管理器-->
    <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>

六、纯注解的改造

1. SpringConfiguration

package config;

import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 这个类就是spring的配置类,相当于bean.xml
 *
 * @Author veeja
 * 2020/5/15 21:48
 */
@Configuration
@ComponentScan("com.veeja")
@Import({JdbcConfig.class, TransactionConfig.class})
@PropertySource(value = "jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}

2. JdbcConfig

package config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 和连接数据库相关的数据类
 *
 * @Author veeja
 * 2020/5/15 21:51
 */
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建JdbcTemplate对象
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 创建一个数据源对象
     *
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(driver);

        dataSource.setUrl(url);

        dataSource.setUsername(username);

        dataSource.setPassword(password);
        return dataSource;
    }
}

3. jdbcConfig.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
jdbc.username=root
jdbc.password=0000

4. TransactionConfig

package config;

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

import javax.sql.DataSource;

/**
 * 和事务相关的配置类
 * @Author veeja
 * 2020/5/15 22:06
 */
public class TransactionConfig {
    /**
     * 用于创建事务管理器对象
     * @param dataSource
     * @return
     */
    @Bean(name ="transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

5. 测试类的改造

package com.veeja.test;


import com.veeja.service.IAccountService;
import config.SpringConfiguration;
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;

/**
 * @Author veeja
 * 2020/5/15 18:11
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService accountService;

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

七、编程式事务(非重点,很少用)

示例:

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

    <!--配置账户的业务层 accountService-->
    <bean id="accountService" class="com.veeja.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="transactionTemplate" ref="transactionTemplate"></property>
    </bean>

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.veeja.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0000"></property>
    </bean>

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

    <!--配置事务模板对象-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

</beans>

业务层改造:

package com.veeja.service.impl;

import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import com.veeja.service.IAccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;


/**
 * 账户的业务层实现类
 *
 * @author veeja
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    private TransactionTemplate transactionTemplate;

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

    @Override
    public Account findAccountById(Integer accountId) {
        return transactionTemplate.execute(new TransactionCallback<Account>() {
            @Override
            public Account doInTransaction(TransactionStatus status) {
                return accountDao.findAccountById(accountId);
            }
        });

    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                /*
                 * 2.执行操作
                 * 2.1.根据名称查询转出账户
                 * 2.2.根据名称查询转入账户
                 * 2.3.转出账户减钱
                 * 2.4.转入账户加钱
                 * 2.5.更新转出账户
                 * 2.6.更新转入账户
                 */
                Account source = accountDao.findAccountByName(sourceName);
                Account target = accountDao.findAccountByName(targetName);
                source.setMoney(source.getMoney() - money);
                target.setMoney(target.getMoney() + money);
                accountDao.updateAccount(source);
                int i = 1 / 0;
                accountDao.updateAccount(target);
                return null;
            }
        });


    }
}


END.
学完了学完了。八天时间!!!

2020年5月15日
今天李美美考上南开的研究生了。我实在是太开心了!!!
哈哈哈哈哈

veeja 0:15:58 我看完了啊
veeja 0:15:59 哈哈哈哈
李美美 0:16:11 我还没发呢
veeja 0:16:14 最后一节 是布置了点作业
veeja 0:16:19 我说我的视频
李美美 0:16:20 这都是一种仪式感
李美美 0:16:31 八天不到

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值