Spring(七)----Spring的聲明式事務控制

一、概述

我們知道,持久層處理dao請求,業務層處理業務邏輯,那麼事物的控制肯定需要在業務層。spring爲我們提供了一組事務控制的API,用來控制事務。

spring的事務控制分別有聲明式控制和編程式事務控制,編程式事務控制使用的很少,一般都是使用聲明式事務控制。

進行事務的控制使用的對象是DataSourceTransactionManager

二、基於xml的事務控制

1.導入座標依賴
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
</dependency>

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

spring-tx是Spring的事務控制的jar包。

2.創建數據庫

我是用銀行的轉賬這個案例,每次一講到事務就必用銀行轉賬案例(笑哭)

CREATE DATABASE USER;
CREATE TABLE account(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20) NOT NULL,
	money DOUBLE
);
3.創建實體類
/**
 * 賬戶的實體類
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

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

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

要實現銀行轉賬,那麼需要findAllByName、update、save方法

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {

    /**
     * 根據名稱查詢賬戶
     * @param accountName
     * @return
     */
    Account findAccountByName(String accountName);

    /**
     * 更新賬戶
     * @param account
     */
    void updateAccount(Account account);
}
5.編寫dao實現類

在實現類裏,由於還沒有整合mybatis那麼我們使用的是spring的jdbcTemplate來幫我們執行sql

/**
 * 賬戶的持久層實現類
 */
public class AccountDaoImpl implements AccountDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

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

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

6.編寫service接口以及實現類
public interface AccountService {
    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);


    /**
     * 轉賬
     * @param sourceName        轉出賬戶名稱
     * @param targetName        轉入賬戶名稱
     * @param money             轉賬金額
     */
    void transfer(String sourceName,String targetName,Double money);

}

實現類

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

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


    @Override
    public void saveAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void transfer(String sourceName, String targetName, Double money) {
        System.out.println("transfer....");
        //2.1根據名稱查詢轉出賬戶
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根據名稱查詢轉入賬戶
        Account target = accountDao.findAccountByName(targetName);
        //2.3轉出賬戶減錢
        source.setMoney(source.getMoney() - money);
        //2.4轉入賬戶加錢
        target.setMoney(target.getMoney() + money);
        //2.5更新轉出賬戶
        accountDao.updateAccount(source);

     //       int i=1/0;

        //2.6更新轉入賬戶
        accountDao.updateAccount(target);
    }
}
7.配置xml

注意在spring的xml配置文件中,需要導入aop和事務的約束

<?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">
<!--    &lt;!&ndash;將Dao交給Spring的ioc容器管理&ndash;&gt;-->
<!--    <bean id="accountDao" class="com.SpringDemo4.dao.impl.AccountDaoImpl"></bean>-->

    <!--將Spring的jdbcTemplate交給Spring的ioc容器管理-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數據源 使用spring的內置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///user"></property>
        <property name="username" value="root"></property>
        <property name="password" value="213213"></property>
    </bean>
    
    <!--配置dao-->
    <bean id="accountDao" class="com.SpringDemo4.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    
    <!--配置service-->
    <bean id="accountService" class="com.SpringDemo4.sercice.Impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    
    <!--配置事務管理器-->
    <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!--配置事務的通知-->
    <tx:advice id="txAdvice" transaction-manager="DataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置aop--->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.SpringDemo4.sercice.Impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

配置聲明式事務的步驟:

  1. 將DataSourceTransactionManager交給ioc容器,這個對象是管理事務的對象
  2. 配置事務的通知,tx:advice配置事務通知,其下的子標籤tx:attributes用於配置事務的屬性:
  • read-only:是否是隻讀事務。默認 false,不只讀
  • isolation:指定事務的隔離級別。默認值是使用數據庫的默認隔離級別。
  • propagation:指定事務的傳播行爲
  • timeout:指定超時時間。默認值爲:-1。永不超時
  • rollback-for:用於指定一個異常,當執行產生該異常時,事務回滾。產生其他異常,事務不回滾。 沒有默認值,任何異常都回滾。
  • no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時,事務回滾。沒有默認值,任何異常都回滾
  1. 配置aop切入點表達式
8.測試
	 @Test
    public void testTransfer(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        accountService.transfer("zhangsan","lisi",100d);
    }

三、基於註解的事務控制

使用基於註解的配置,只需要是使用一個註解@Transactional,非常方便。配置註解的事務控制,只需要改變xml配置文件裏的內容和業務層代碼上添加一個註解即可

1.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">
<!--    &lt;!&ndash;將Dao交給Spring的ioc容器管理&ndash;&gt;-->
<!--    <bean id="accountDao" class="com.SpringDemo4.dao.impl.AccountDaoImpl"></bean>-->
    <!--配置掃描的包-->
    <context:component-scan base-package="com.SpringDemo4.sercice"></context:component-scan>

    <!--將Spring的jdbcTemplate交給Spring的ioc容器管理-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數據源 使用spring的內置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///user"></property>
        <property name="username" value="root"></property>
        <property name="password" value="213213"></property>
    </bean>

    <!--配置dao-->
    <bean id="accountDao" class="com.SpringDemo4.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--配置service-->
    <bean id="accountService" class="com.SpringDemo4.sercice.Impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

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

    <!-- 開啓 spring 對註解事務的支持 -->
    <tx:annotation-driven transaction-manager="DataSourceTransactionManager"/>

</beans>
2.service實現類
@Transactional
public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

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


    @Override
    public void saveAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }


    @Override
    public void transfer(String sourceName, String targetName, Double money) {
        System.out.println("transfer....");
        //2.1根據名稱查詢轉出賬戶
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根據名稱查詢轉入賬戶
        Account target = accountDao.findAccountByName(targetName);
        //2.3轉出賬戶減錢
        source.setMoney(source.getMoney() - money);
        //2.4轉入賬戶加錢
        target.setMoney(target.getMoney() + money);
        //2.5更新轉出賬戶
        accountDao.updateAccount(source);

            int i=1/0;

        //2.6更新轉入賬戶
        accountDao.updateAccount(target);
    }
}

Transactional註解和在基於xml的方式中配置tx:attributes中的內容一致。

3.總結

總結一下基於註解的事務控制

  1. 在xml文件中開啓掃描的包,並開啓對象事務控制的支持
  <!--配置掃描的包-->
    <context:component-scan base-package="com.SpringDemo4.sercice"></context:component-scan>  
	<!-- 開啓 spring 對註解事務的支持 -->
    <tx:annotation-driven transaction-manager="DataSourceTransactionManager"/>
  1. 配置事務管理器
 <!--配置事務管理器-->
    <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

在需要事務控制類上添加@Transactional註解,裏面的屬性和基於xml的方式中配置tx:attributes中的內容一致。

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