Spring 事務管理的使用


 

Spring提供了2種事務管理

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

 

 


 

 

基於轉賬的demo

dao層

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

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:

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:

#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層的這句代碼取消注釋,會出現錢轉丟的情況(對方收不到錢)。

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

 

 


 

 

編程式事務管理

編程式事務管理,顧名思義需要自己寫代碼。

自己寫代碼很麻煩,spring把代碼封裝在了TransactionTemplate類中,方便了很多。

 

(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接口類型的變量,只需實現一個方法:把原來處理業務的代理都放到這個方法中。

 
        

 

(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壓縮包的下載可參考:https://www.cnblogs.com/chy18883701161/p/11108542.html

 

 

 

  • 配置了事務的注解驅動<tx:annotation-driven transaction-manager="transactionManager" /> ,但一次都沒有標注@Transactional,即一次都沒有使用事務,會報錯:
通配符的匹配很全面, 但無法找到元素 'tx:annotation-driven' 的聲明。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM