亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring中的事務控制知識總結

 更新時間:2021年06月04日 15:06:58   作者:Xiu Yan  
我們講了轉賬方法存在著事務問題,當在業(yè)務層方法更新轉入賬戶時發(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);
}
/**
 * 轉賬的業(yè)務層實現(xiàn)類
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    /**
     * 轉賬
     * @param sourceName    轉出賬戶名稱
     * @param targetName    轉入賬戶名稱
     * @param money         轉賬金額
     */
    public void transfer(String sourceName, String targetName, Float money) {
            //1. 根據(jù)名稱查詢轉出賬戶
            Account source = accountDao.findAccountByName(sourceName);//  1. 第一次事務,提交
            //2. 根據(jù)名稱查詢轉入賬戶
            Account target = accountDao.findAccountByName(targetName);//  2. 第二次事務提交
            //3. 轉出賬戶減錢
            source.setMoney(source.getMoney()-money);
            //4. 轉入賬戶加錢
            target.setMoney(target.getMoney()+money);
            //5. 更新轉出賬戶
            accountDao.updateAccount(source);  //  3. 第三次事務提交
            int i = 1/0;  					   //  4. 報異常
            //6. 更新轉入賬戶
            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("結果集不唯一");
        }
        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 內置數(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.建立事務通知 與 切入點表達式的對應關系

<!--配置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 標簽的內部

  • isolation: 用于指定事務的隔離級別。默認值是DEFAULT,表示使用數(shù)據(jù)庫的默認隔離級別。
  • propagation: 用于指定事務的傳播行為。默認值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以選擇SUPPORT。
  • read-only: 用于指定事務是否只讀。只有查詢方法才能設置為true。默認值時false,表示讀寫。
  • timeout: 用于指定事務的超時時間。默認值是-1,表示永不超時。如果指定了數(shù)值,則以秒為單位。
  • rollback-for: 用于指定一個異常,當產生該異常時,事務不回滾,產生其他異常,事務不回滾。沒有默認值。表示任何異常都回滾。
  • no-rollback-for: 用于指定一個異常,當產生該異常時,事務不回滾,產生其他異常時,事務回滾。沒有默認值。表示任何異常都回滾。
<!--配置事務的通知-->
<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>

測試結果:

在這里插入圖片描述

三、基于注解的事務控制

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)類:

/**
 * 轉賬的業(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;
	
	......
}

測試結果如下:

在這里插入圖片描述

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

相關文章

  • Java反轉字符串的10種方法

    Java反轉字符串的10種方法

    這篇文章主要介紹了Java反轉字符串的10種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,下面我們來一起學習一下吧
    2019-06-06
  • Java線程等待喚醒幾種方法小結

    Java線程等待喚醒幾種方法小結

    線程等待和喚醒有三種實現(xiàn)方法,分別是Object類中的wait、notify,Condition類中的await、signal,LockSupport類中的park、unpark方法,感興趣的可以了解一下
    2023-10-10
  • Java遞歸實現(xiàn)字符串全排列與全組合

    Java遞歸實現(xiàn)字符串全排列與全組合

    這篇文章主要為大家詳細介紹了Java遞歸實現(xiàn)字符串全排列與全組合,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • SpringBoot整合Hbase的實現(xiàn)示例

    SpringBoot整合Hbase的實現(xiàn)示例

    這篇文章主要介紹了SpringBoot整合Hbase的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • 通過Java實現(xiàn)對PDF頁面的詳細設置

    通過Java實現(xiàn)對PDF頁面的詳細設置

    這篇文章主要介紹了通過Java實現(xiàn)對PDF頁面的詳細設置,下面的示例將介紹通過Java編程來對PDF頁面進行個性化設置的方法,包括設置頁面大小、頁邊距、紙張方向、頁面旋轉等,需要的朋友可以參考下
    2019-07-07
  • Springboot+MybatisPlus實現(xiàn)帶驗證碼的登錄

    Springboot+MybatisPlus實現(xiàn)帶驗證碼的登錄

    本文主要介紹了Springboot+MybatisPlus實現(xiàn)帶驗證碼的登錄,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-05-05
  • 基于SSM框架實現(xiàn)簡單的登錄注冊的示例代碼

    基于SSM框架實現(xiàn)簡單的登錄注冊的示例代碼

    這篇文章主要介紹了基于SSM框架實現(xiàn)簡單的登錄注冊的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12
  • Java實現(xiàn)分頁代碼

    Java實現(xiàn)分頁代碼

    這篇文章主要為大家詳細介紹了Java實現(xiàn)分頁代碼,提高查詢效率,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • Java實現(xiàn)上傳Excel文件并導入數(shù)據(jù)庫

    Java實現(xiàn)上傳Excel文件并導入數(shù)據(jù)庫

    這篇文章主要介紹了在java的基礎上學習上傳Excel文件并導出到數(shù)據(jù)庫,感興趣的小伙伴不要錯過奧
    2021-09-09
  • spring boot中interceptor攔截器未生效的解決

    spring boot中interceptor攔截器未生效的解決

    這篇文章主要介紹了spring boot中interceptor攔截器未生效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09

最新評論