最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring中的事務控制知識總結(jié)

 更新時間:2021年06月04日 15:06:58   作者:Xiu Yan  
我們講了轉(zhuǎn)賬方法存在著事務問題,當在業(yè)務層方法更新轉(zhuǎn)入賬戶時發(fā)現(xiàn)異常,更新收款方賬戶則會出錯.當時是通過自定義事務管理器進行整體事務的處理.其實Spring 提供了業(yè)務層的事務處理解決方案,并且 Spring 的事務控制都是基于 AOP 的,需要的朋友可以參考下

一、環(huán)境準備

為了演示 Spring 中的事務控制,我們創(chuàng)建一個空項目,項目目錄如下:

在這里插入圖片描述

導入依賴:

<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>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.6</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>
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-test</artifactId>
	    <version>5.0.2.RELEASE</version>
	</dependency>
</dependencies>

業(yè)務層及其實現(xiàn)類:

/**
 * 賬戶的業(yè)務層接口
 */
public interface IAccountService {

    void transfer(String sourceName, String targetName, Float money);
}
/**
 * 轉(zhuǎn)賬的業(yè)務層實現(xiàn)類
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    /**
     * 轉(zhuǎn)賬
     * @param sourceName    轉(zhuǎn)出賬戶名稱
     * @param targetName    轉(zhuǎn)入賬戶名稱
     * @param money         轉(zhuǎn)賬金額
     */
    public void transfer(String sourceName, String targetName, Float money) {
            //1. 根據(jù)名稱查詢轉(zhuǎn)出賬戶
            Account source = accountDao.findAccountByName(sourceName);//  1. 第一次事務,提交
            //2. 根據(jù)名稱查詢轉(zhuǎn)入賬戶
            Account target = accountDao.findAccountByName(targetName);//  2. 第二次事務提交
            //3. 轉(zhuǎn)出賬戶減錢
            source.setMoney(source.getMoney()-money);
            //4. 轉(zhuǎn)入賬戶加錢
            target.setMoney(target.getMoney()+money);
            //5. 更新轉(zhuǎn)出賬戶
            accountDao.updateAccount(source);  //  3. 第三次事務提交
            int i = 1/0;  					   //  4. 報異常
            //6. 更新轉(zhuǎn)入賬戶
            accountDao.updateAccount(target);  //  5. 事務不執(zhí)行
    }
}

賬戶持久層及其接口:

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

    /**
     * 根據(jù)Id查詢賬戶
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

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

    /**
     * 更新賬戶
     * @param account
     */
    void updateAccount(Account account);
}
/**
 * 賬戶的持久層實現(xiàn)類
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    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);
    }


    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("結(jié)果集不唯一");
        }
        return accounts.get(0);
    }


    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}

這里配置的是 Spring 內(nèi)置數(shù)據(jù)源,當然也可以應用 JdbcTemplate。

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"
       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">
        
    <!--配置業(yè)務層-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置賬戶的持久層-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數(shù)據(jù)源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/springdb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="000000"></property>
    </bean>

</beans>

二、基于 XML 的事務控制

Spring 中基于 xml 的聲明式事務控制配置步驟

1.配置事務管理器

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

2.配置事務的通知 (需要導入事務的約束 tx 和 aop 的名稱空間和約束)
使用 tx:advice 標簽配置事務通知

屬性:

id:給事務通知起一個唯一標識
transaction-manager:給事務通知提供一個事務管理器引用

<!--配置事務的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>

3.配置AOP的通用切入點表達式

<!--配置AOP的通用切入點表達式-->
<aop:config>
	<aop:pointcut id="pt1" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut>
</aop:config>

4.建立事務通知 與 切入點表達式的對應關(guān)系

<!--配置AOP的通用切入點表達式-->
<aop:config>
	<aop:pointcut id="pt1" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>

5.配置事務的屬性

在事務的通知 tx:advice 標簽的內(nèi)部

  • isolation: 用于指定事務的隔離級別。默認值是DEFAULT,表示使用數(shù)據(jù)庫的默認隔離級別。
  • propagation: 用于指定事務的傳播行為。默認值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以選擇SUPPORT。
  • read-only: 用于指定事務是否只讀。只有查詢方法才能設置為true。默認值時false,表示讀寫。
  • timeout: 用于指定事務的超時時間。默認值是-1,表示永不超時。如果指定了數(shù)值,則以秒為單位。
  • rollback-for: 用于指定一個異常,當產(chǎn)生該異常時,事務不回滾,產(chǎn)生其他異常,事務不回滾。沒有默認值。表示任何異常都回滾。
  • no-rollback-for: 用于指定一個異常,當產(chǎn)生該異常時,事務不回滾,產(chǎn)生其他異常時,事務回滾。沒有默認值。表示任何異常都回滾。
<!--配置事務的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" read-only="false"></tx:method>
        <tx:method name="find*" propagation="REQUIRED" read-only="false"></tx:method> <!--優(yōu)先級高于通配符 * -->
    </tx:attributes>
</tx:advice>

最終 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"
       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">
    <!--配置業(yè)務層-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置賬戶的持久層-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數(shù)據(jù)源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/springdb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="000000"></property>
    </bean>
   
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事務的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"></tx:method>
            <tx:method name="find*" propagation="REQUIRED" read-only="false"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP的通用切入點表達式-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

測試結(jié)果:

在這里插入圖片描述

三、基于注解的事務控制

Spring 中基于 xml 的聲明式事務控制配置步驟

1.配置事務管理器

2.開啟 Spring 對注解事物的支持

3.在需要事務支持的地方使用 @Transactional 注解

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">
        
    <!--配置容器時要掃描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數(shù)據(jù)源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/springdb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="000000"></property>
    </bean>
    
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--開啟spring對注解事物的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>

賬戶業(yè)務層實現(xiàn)類:

/**
 * 轉(zhuǎn)賬的業(yè)務層實現(xiàn)類
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {
	......
}

賬戶持久層實現(xiàn)類:

/**
 * 賬戶的持久層實現(xiàn)類
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
	
	......
}

測試結(jié)果如下:

在這里插入圖片描述

到此這篇關(guān)于Spring中的事務控制知識總結(jié)的文章就介紹到這了,更多相關(guān)Spring事務控制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • RxJava2 Scheduler使用實例深入解析

    RxJava2 Scheduler使用實例深入解析

    這篇文章主要為大家介紹了RxJava2 Scheduler使用實例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • java中邏輯控制舉例具體講解

    java中邏輯控制舉例具體講解

    Java程序邏輯控制通俗說就是對代碼執(zhí)行順序的控制,這篇文章主要給大家介紹了關(guān)于java中邏輯控制的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • java 文件上傳到讀取文件內(nèi)容的實例

    java 文件上傳到讀取文件內(nèi)容的實例

    今天小編就為大家分享一篇java 文件上傳到讀取文件內(nèi)容的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 深入解析Spring Cloud內(nèi)置的Zuul過濾器

    深入解析Spring Cloud內(nèi)置的Zuul過濾器

    這篇文章主要給大家深入的介紹了Spring Cloud內(nèi)置的Zuul過濾器的相關(guān)資料,文中給大家介紹的很詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。
    2017-02-02
  • java有序二叉樹的刪除節(jié)點方式

    java有序二叉樹的刪除節(jié)點方式

    文章描述了在二叉樹中刪除節(jié)點的三種情況及其對應的操作步驟,通過遞歸找到節(jié)點及其父節(jié)點,并根據(jù)節(jié)點的子樹情況(無子樹、單子樹、雙子樹)進行相應的刪除操作,文章還提供了一個測試類來驗證刪除操作的正確性
    2024-12-12
  • Java 超詳細講解數(shù)據(jù)結(jié)構(gòu)的應用

    Java 超詳細講解數(shù)據(jù)結(jié)構(gòu)的應用

    數(shù)據(jù)結(jié)構(gòu)是計算機存儲、組織數(shù)據(jù)的方式。數(shù)據(jù)結(jié)構(gòu)是指相互之間存在一種或多種特定關(guān)系的數(shù)據(jù)元素的集合,讓我們一起來了解數(shù)據(jù)結(jié)構(gòu)是如何應用的
    2022-04-04
  • Servlet編程第一步之從零構(gòu)建Hello?World應用詳細步驟+圖解

    Servlet編程第一步之從零構(gòu)建Hello?World應用詳細步驟+圖解

    本文詳細介紹了Servlet和maven的基本概念及其在JavaWeb開發(fā)中的應用,首先解釋了Servlet是一個在服務器上處理請求的Java程序,然后介紹了maven作為管理和構(gòu)建Java項目的工具,需要的朋友可以參考下
    2024-10-10
  • Java hashCode() 方法詳細解讀

    Java hashCode() 方法詳細解讀

    Java.lang.Object 有一個hashCode()和一個equals()方法,這兩個方法在軟件設計中扮演著舉足輕重的角色,本文對hashCode()方法深入理解,希望能幫助大家
    2016-07-07
  • Java組件FileUpload上傳文件實現(xiàn)代碼

    Java組件FileUpload上傳文件實現(xiàn)代碼

    這篇文章主要為大家詳細介紹了Java組件FileUpload上傳文件實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-06-06
  • 詳解springboot設置默認參數(shù)Springboot.setDefaultProperties(map)不生效解決

    詳解springboot設置默認參數(shù)Springboot.setDefaultProperties(map)不生效解決

    這篇文章主要介紹了詳解springboot設置默認參數(shù)Springboot.setDefaultProperties(map)不生效解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07

最新評論

施秉县| 宜城市| 鹤壁市| 大田县| 炉霍县| 和田县| 会宁县| 鄢陵县| 广东省| 巴塘县| 涡阳县| 长子县| 五峰| 盘山县| 广灵县| 大埔区| 海南省| 浪卡子县| 新河县| 泗洪县| 岳阳县| 喜德县| 陆良县| 贵港市| 遵化市| 政和县| 潞西市| 武穴市| 中山市| 沧源| 昆山市| 荣成市| 潞城市| 托克逊县| 乌拉特后旗| 夏邑县| 慈溪市| 沙河市| 钦州市| 光山县| 阿拉善左旗|