Spring 事務管理的使用

 

Spring提供了2種事務管理html

  • 編程式的
  • 聲明式的(重點):包括xml方式、註解方式(推薦)

 

 


 

 

基於轉帳的demo

dao層

新建包com.chy.dao,包下新建接口AccountDao、實現類AccountDaoImpl:mysql

public interface AccountDao {
    //查詢用戶帳戶上的餘額
    public double queryMoney(int id);
    //減小用戶帳戶上的餘額
    public void reduceMoney(int id, double amount);
    //增長用戶帳戶上的餘額
    public void addMoney(int id, double amount);
}
@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public double queryMoney(int id) {
        String sql = "select money from account_tb where id=?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        double money = jdbcTemplate.queryForObject(sql, double.class,id);
        return money;
    }

    @Override
    public void reduceMoney(int id, double account) {
        double money = queryMoney(id);
        money -= account;
        if (money>=0){
            String sql = "update account_tb set money=? where id=?";
            JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
            jdbcTemplate.update(sql, money, id);
        }
        //此處省略餘額不足時的處理
    }

    @Override
    public void addMoney(int id, double account) {
        double money = queryMoney(id);
        money += account;
        String sql = "update account_tb set money=? where id=?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        jdbcTemplate.update(sql, money, id);
    }
}

 

 

service層

新建包com.chy.service,包下新建接口TransferService、實現類TransferServiceImpl:spring

public interface TransferService {
    public void transfer(int from,int to,double account);
}
@Service
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;
    
    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(int from, int to, double account) {
        accountDao.reduceMoney(from,account);
        // System.out.println(1/0);
        accountDao.addMoney(to,account);
    }
}

 

 

數據庫鏈接信息

src下新建db.properties:sql

#mysql數據源配置
url=jdbc:mysql://localhost:3306/my_db?serverTimezone=GMT
user=chy
password=abcd

 

 

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: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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 引入數據庫配置信息 -->
    <context:property-placeholder location="db.properties" />

    <!-- 使用包掃描-->
    <context:component-scan base-package="com.chy.dao,com.chy.service" />

    <!-- 配置數據源,此處使用jdbc數據源 -->
    <bean name="jdbcDataSource" class="com.mysql.cj.jdbc.MysqlDataSource">
        <property name="url" value="${url}" />
        <property name="user" value="${user}" />
        <property name="password" value="${password}" />
    </bean>

    <!-- 配置AccountDaoImpl,注入數據源 -->
    <bean name="accountDaoImpl" class="com.chy.dao.AccountDaoImpl">
        <!--注入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>
</beans>

 

 

測試

新建包com.chy.test,包下新建主類Test:數據庫

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        TransferServiceImpl transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferServiceImpl.class);
        transferServiceImpl.transfer(1,2,1000);

 

 

以上是未使用事務管理的,將service層的這句代碼取消註釋,會出現錢轉丟的狀況(對方收不到錢)。express

// System.out.println(1/0);

 

 


 

 

編程式事務管理

編程式事務管理,顧名思義須要本身寫代碼。編程

本身寫代碼很麻煩,spring把代碼封裝在了TransactionTemplate類中,方便了不少。app

 

(1)事務須要添加到業務層(service),修改TransferServiceImpl類以下:

@Service
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

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

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

    @Override
    public void transfer(int from, int to, double account) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountDao.reduceMoney(from, account);
                // System.out.println(1 / 0);
 accountDao.addMoney(to, account); } });
    }
}
  • 注入事務管理模板TransactionTemplate(成員變量+setter方法)。
  • 在處理業務的方法中寫:
transactionTemplate.execute(new TransactionCallbackWithoutResult() {  });

使用匿名內部類傳入一個TransactionCallbackWithoutResult接口類型的變量,只需實現一個方法:把原來處理業務的代理都放到這個方法中。ide

 

 

(2)在xml中配置事務管理、事務管理模板

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!-- 配置事務管理模板-->
    <bean class="org.springframework.transaction.support.TransactionTemplate">
        <!-- 注入事務管理器 -->
        <property name="transactionManager" ref="transactionManager" />
    </bean>

 

 

把下面這句代碼取消註釋,運行,不會出現錢轉丟的狀況(執行失敗,自動回滾):測試

// System.out.println(1/0);

 

 


 

 

聲明式事務管理(此節必看)

聲明式事務管理,無論是基於xml,仍是基於註解,都有如下3個點要注意:

  • 底層是使用AOP實現的(在Spring中使用AspectJ),須要把AspectJ相關的jar包添加進來。

 

  • 由於咱們的service層通常寫成接口——實現類的形式,既然實現了接口,基於動態代理的AspectJ代理的天然是接口,因此只能使用接口來聲明:
TransferService transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferService.class);

紅色標出的2處只能使用接口。

 

  • 在配置xml時有一些新手必遇到的坑,若是在配置xml文件時遇到了問題,可滑到最後面查看我寫的解決方式。

 

 


 

 

基於xml的聲明式事務管理

xml配置:

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!-- 配置加強-->
    <!-- 此處只能用id,不能用name。transaction-manager指定要引用的事務管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 配置要添加事務的方法,直接寫方法名便可。能夠有多個method元素,可使用通配符* -->
            <tx:method name="transfer" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置aop-->
    <aop:config>
        <!-- 配置切入點-->
        <aop:pointcut id="transferPointCut" expression="execution(* com.chy.service.TransferServiceImpl.transfer(..))"/>
        <!--指定要引用的<tx:advice>,指定切入點。切入點能夠point-ref引用,也能夠pointcut現配。能夠有多個advisor元素。 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="transferPointCut"/>
    </aop:config>

 

 


 

 

說明

<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT" read-only="false" />
  • propagation 指定事務的傳播行爲,默認爲REQUIRED

  • isolation 指定事務的隔離級別

  • read-only 是否只讀,讀=>查詢,寫=>增刪改。默認爲false——讀寫。

  • timeout  事務的超時時間,-1表示永不超時。

這4個屬性通常都不用設置,使用默認值便可。固然,只查的時候,能夠設置read-only="true"。

 

 

常見的3種配置方式:

            <tx:method name="transfer" />
<tx:method name="*" />
<tx:method name="save*" /> <tx:method name="find*" read-only="false"/> <tx:method name="update*" /> <tx:method name="delete*" />
  • 指定具體的方法名
  • 用*指定全部方法
  • 指定以特定字符串開頭的方法(咱們寫的dao層方法通常都以這些詞開頭)

由於要配合aop使用,篩選範圍是切入點指定的方法,不是項目中全部的方法。

 

 

好比

<tx:method name="save*" />
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.chy.service.TransferServiceImpl.*(..))" />

切入點是TransferServiceImpl類中的全部方法,是在TransferServiceImpl類全部方法中找到以save開頭的全部方法,給其添加事務。

 

 


 

 

基於註解的聲明式事務管理(推薦)

(1)xml配置

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!--啓用事務管理的註解,並指定要使用的事務管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

 

 

(2)使用@Transactional標註

@Service
// @Transactional
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;

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

    @Override
    @Transactional public void transfer(int from, int to, double account) {
        accountDao.reduceMoney(from, account);
        // System.out.println(1 / 0);
        accountDao.addMoney(to, account);
    }
}

能夠標註在業務層的實現類上,也能夠標註在處理業務的方法上。

標註在類上,會給這個全部的業務方法都添加事務;標註在業務方法上,則只給這個方法添加事務。

 

 

一樣能夠設置傳播行爲、隔離級別、是否只讀:

@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)

 

基於註解的聲明式事務管理是最簡單的,推薦使用。

 

 


 

 

聲明式事務管理,配置xml時的坑

  • <tx:advice>、<tx:annotation-driven>的代碼提示不對、配置沒錯但仍然顯式紅色

緣由:IDEA自動引入的約束不對。

IDEA會自動引入所需的約束,但spring事務管理所需的約束,IDEA引入的不對。

 

 

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

看我紅色標出的部分(需拖動滾動條查看最右邊),這是IDEA自動引入的tx的約束,這是舊版本的約束,已經無效了。

 

 

新版本的約束:

xmlns:tx="http://www.springframework.org/schema/tx"

xsi裏對應的部分也要修改:

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

能夠在錯誤約束的基礎上改,也能夠添加。

 

 

若是沒有修改xsi中對應的部分,會報下面的錯:

通配符的匹配很全面, 但沒法找到元素 'tx:advice' 的聲明。
通配符的匹配很全面, 但沒法找到元素 'tx:annotation-driven' 的聲明。

 

 

上面提供的約束是目前版本的約束,之後可能會變。最好在官方文檔中找,有2種方式:

(1)http://www.springframework.org/schema/tx/spring-tx.xsd     可修改此url查看其它約束

 

(2)若是下載了spring的壓縮包,可在schema文件夾下查看約束。

spring壓縮包的下載可參考:http://www.javashuo.com/article/p-yscxladi-ko.html

相關文章
相關標籤/搜索