spring架構學習筆記7:交易管理及案例,spring學習筆記

來源:互聯網
上載者:User

spring架構學習筆記7:交易管理及案例,spring學習筆記

Spring提供了一套管理項目中的事務的機制

以前寫過一篇簡單的介紹事務的隨筆:http://www.cnblogs.com/xuyiqing/p/8430214.html

還有一篇Hibernate的交易管理:http://www.cnblogs.com/xuyiqing/p/8449167.html

可以做個對比

 

Spring管理事務特有的屬性:

事務傳播行為:事務傳播行為(propagation behavior)指的就是當一個事務方法被另一個事務方法調用時,這個事務方法應該如何進行。 

例如:methodA事務方法調用methodB事務方法時,methodB是繼續在調用者methodA的事務中運行呢,還是為自己開啟一個新事務運行,這就是由methodB的事務傳播行為決定的。

 

1、PROPAGATION_REQUIRED:如果當前沒有事務,就建立一個新事務,如果當前存在事務,就加入該事務,該設定是最常用的設定。

2、PROPAGATION_SUPPORTS:支援當前事務,如果當前存在事務,就加入該事務,如果當前不存在事務,就以非事務執行。‘

3、PROPAGATION_MANDATORY:支援當前事務,如果當前存在事務,就加入該事務,如果當前不存在事務,就拋出異常。

4、PROPAGATION_REQUIRES_NEW:建立新事務,無論當前存不存在事務,都建立新事務。

5、PROPAGATION_NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。

6、PROPAGATION_NEVER:以非事務方式執行,如果當前存在事務,則拋出異常。

7、PROPAGATION_NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行與PROPAGATION_REQUIRED類似的操作

 

 

接下來示範事務案例:簡單類比轉賬

需要的包:

建立一張表,放入資料:

package dao;public interface AccountDao {        //加錢    void increaseMoney(Integer id,Double money);    //減錢    void decreaseMoney(Integer id,Double money);}
package dao;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao  {    @Override    public void increaseMoney(Integer id, Double money) {                getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id);            }    @Override    public void decreaseMoney(Integer id, Double money) {        getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);    }}
package service;public interface AccountService {        //轉賬方法    void transfer(Integer from,Integer to,Double money);    }
package service;import dao.AccountDao;public class AccountServiceImpl implements AccountService {    private AccountDao ad;    @Override    public void transfer(final Integer from, final Integer to, final Double money) {        // 減錢        ad.decreaseMoney(from, money);        // 加錢        ad.increaseMoney(to, money);    }    public void setAd(AccountDao ad) {        this.ad = ad;    }}
package tx;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import service.AccountService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo {        @Resource(name="accountService")    private AccountService as;        @Test    public void fun1(){                as.transfer(1, 2, 100d);            }}

設定檔:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "><!-- 指定spring讀取db.properties配置 --><context:property-placeholder location="classpath:db.properties"  /><!-- 事務核心管理器,封裝了所有事務操作. 依賴於串連池 --><bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >    <property name="dataSource" ref="dataSource" ></property></bean><!-- 配置事務通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager" >    <tx:attributes>        <!-- 以方法為單位,指定方法應用什麼事務屬性            isolation:隔離等級            propagation:傳播行為            read-only:是否唯讀            其他方法的配置沒有用到,但它們通常是統一配置         -->        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />                <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />    </tx:attributes></tx:advice><!-- 配置織入 --><aop:config  >    <!-- 配置切點運算式 -->    <aop:pointcut expression="execution(* service.*ServiceImpl.*(..))" id="txPc"/>    <!-- 配置切面 : 通知+切點             advice-ref:通知的名稱             pointcut-ref:切點的名稱     -->    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" /></aop:config><!-- 1.將串連池 --><bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>    <property name="driverClass" value="${jdbc.driverClass}" ></property>    <property name="user" value="${jdbc.user}" ></property>    <property name="password" value="${jdbc.password}" ></property></bean><!-- 2.Dao--><bean name="accountDao" class="dao.AccountDaoImpl" >    <property name="dataSource" ref="dataSource" ></property></bean><!-- 3.Service--><bean name="accountService" class="service.AccountServiceImpl" >    <property name="ad" ref="accountDao" ></property></bean>  </beans>

db.properties

jdbc.jdbcUrl=jdbc:mysql:///mybasejdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=xuyiqing

 

運行Demo後結果:

 

轉賬成功!

 

補充:

可以採用註解方式代替XML設定檔:

設定檔只要一行即可:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "><!-- 指定spring讀取db.properties配置 --><context:property-placeholder location="classpath:db.properties"  /><!-- 事務核心管理器,封裝了所有事務操作. 依賴於串連池 --><bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >    <property name="dataSource" ref="dataSource" ></property></bean><!-- 事務模板對象 --><bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >    <property name="transactionManager" ref="transactionManager" ></property></bean><!-- 開啟使用註解管理aop事務 --><tx:annotation-driven/><!-- 1.將串連池 --><bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>    <property name="driverClass" value="${jdbc.driverClass}" ></property>    <property name="user" value="${jdbc.user}" ></property>    <property name="password" value="${jdbc.password}" ></property></bean><!-- 2.Dao--><bean name="accountDao" class="dao.AccountDaoImpl" >    <property name="dataSource" ref="dataSource" ></property></bean><!-- 3.Service--><bean name="accountService" class="service.AccountServiceImpl" >    <property name="ad" ref="accountDao" ></property></bean>  </beans>
package service;import org.springframework.transaction.annotation.Isolation;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import dao.AccountDao;@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)public class AccountServiceImpl implements AccountService {    private AccountDao ad;    @Override    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)    public void transfer(final Integer from, final Integer to, final Double money) {        // 減錢        ad.decreaseMoney(from, money);        // 加錢        ad.increaseMoney(to, money);    }    public void setAd(AccountDao ad) {        this.ad = ad;    }}

 

 

測試後同樣成功!

Spring架構的學習就到這裡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.