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 八天不到

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章