Spring中的事務(wù)控制知識(shí)總結(jié)
一、環(huán)境準(zhǔn)備
為了演示 Spring 中的事務(wù)控制,我們創(chuàng)建一個(gè)空項(xiàng)目,項(xiàng)目目錄如下:
導(dǎo)入依賴:
<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è)務(wù)層及其實(shí)現(xiàn)類:
/** * 賬戶的業(yè)務(wù)層接口 */ public interface IAccountService { void transfer(String sourceName, String targetName, Float money); }
/** * 轉(zhuǎn)賬的業(yè)務(wù)層實(shí)現(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. 第一次事務(wù),提交 //2. 根據(jù)名稱查詢轉(zhuǎn)入賬戶 Account target = accountDao.findAccountByName(targetName);// 2. 第二次事務(wù)提交 //3. 轉(zhuǎn)出賬戶減錢 source.setMoney(source.getMoney()-money); //4. 轉(zhuǎn)入賬戶加錢 target.setMoney(target.getMoney()+money); //5. 更新轉(zhuǎn)出賬戶 accountDao.updateAccount(source); // 3. 第三次事務(wù)提交 int i = 1/0; // 4. 報(bào)異常 //6. 更新轉(zhuǎn)入賬戶 accountDao.updateAccount(target); // 5. 事務(wù)不執(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); }
/** * 賬戶的持久層實(shí)現(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ù)源,當(dāng)然也可以應(yīng)用 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è)務(wù)層--> <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 的事務(wù)控制
Spring 中基于 xml 的聲明式事務(wù)控制配置步驟
1.配置事務(wù)管理器
<!--配置事務(wù)管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"></bean>
2.配置事務(wù)的通知 (需要導(dǎo)入事務(wù)的約束 tx 和 aop 的名稱空間和約束)
使用 tx:advice 標(biāo)簽配置事務(wù)通知
屬性:
id:給事務(wù)通知起一個(gè)唯一標(biāo)識(shí)
transaction-manager:給事務(wù)通知提供一個(gè)事務(wù)管理器引用
<!--配置事務(wù)的通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
3.配置AOP的通用切入點(diǎn)表達(dá)式
<!--配置AOP的通用切入點(diǎn)表達(dá)式--> <aop:config> <aop:pointcut id="pt1" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut> </aop:config>
4.建立事務(wù)通知 與 切入點(diǎn)表達(dá)式的對(duì)應(yīng)關(guān)系
<!--配置AOP的通用切入點(diǎn)表達(dá)式--> <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.配置事務(wù)的屬性
在事務(wù)的通知 tx:advice 標(biāo)簽的內(nèi)部
- isolation: 用于指定事務(wù)的隔離級(jí)別。默認(rèn)值是DEFAULT,表示使用數(shù)據(jù)庫(kù)的默認(rèn)隔離級(jí)別。
- propagation: 用于指定事務(wù)的傳播行為。默認(rèn)值是REQUIRED,表示一定會(huì)有事務(wù),增刪改的選擇。查詢方法可以選擇SUPPORT。
- read-only: 用于指定事務(wù)是否只讀。只有查詢方法才能設(shè)置為true。默認(rèn)值時(shí)false,表示讀寫。
- timeout: 用于指定事務(wù)的超時(shí)時(shí)間。默認(rèn)值是-1,表示永不超時(shí)。如果指定了數(shù)值,則以秒為單位。
- rollback-for: 用于指定一個(gè)異常,當(dāng)產(chǎn)生該異常時(shí),事務(wù)不回滾,產(chǎn)生其他異常,事務(wù)不回滾。沒(méi)有默認(rèn)值。表示任何異常都回滾。
- no-rollback-for: 用于指定一個(gè)異常,當(dāng)產(chǎn)生該異常時(shí),事務(wù)不回滾,產(chǎn)生其他異常時(shí),事務(wù)回滾。沒(méi)有默認(rèn)值。表示任何異常都回滾。
<!--配置事務(wù)的通知--> <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)先級(jí)高于通配符 * --> </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è)務(wù)層--> <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> <!--配置事務(wù)管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事務(wù)的通知--> <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的通用切入點(diǎn)表達(dá)式--> <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>
測(cè)試結(jié)果:
三、基于注解的事務(wù)控制
Spring 中基于 xml 的聲明式事務(wù)控制配置步驟
1.配置事務(wù)管理器
2.開啟 Spring 對(duì)注解事物的支持
3.在需要事務(wù)支持的地方使用 @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"> <!--配置容器時(shí)要掃描的包--> <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> <!--配置事務(wù)管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--開啟spring對(duì)注解事物的支持--> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> </beans>
賬戶業(yè)務(wù)層實(shí)現(xiàn)類:
/** * 轉(zhuǎn)賬的業(yè)務(wù)層實(shí)現(xiàn)類 */ @Service("accountService") @Transactional public class AccountServiceImpl implements IAccountService { ...... }
賬戶持久層實(shí)現(xiàn)類:
/** * 賬戶的持久層實(shí)現(xiàn)類 */ @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; ...... }
測(cè)試結(jié)果如下:
到此這篇關(guān)于Spring中的事務(wù)控制知識(shí)總結(jié)的文章就介紹到這了,更多相關(guān)Spring事務(wù)控制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合Hbase的實(shí)現(xiàn)示例
這篇文章主要介紹了SpringBoot整合Hbase的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12通過(guò)Java實(shí)現(xiàn)對(duì)PDF頁(yè)面的詳細(xì)設(shè)置
這篇文章主要介紹了通過(guò)Java實(shí)現(xiàn)對(duì)PDF頁(yè)面的詳細(xì)設(shè)置,下面的示例將介紹通過(guò)Java編程來(lái)對(duì)PDF頁(yè)面進(jìn)行個(gè)性化設(shè)置的方法,包括設(shè)置頁(yè)面大小、頁(yè)邊距、紙張方向、頁(yè)面旋轉(zhuǎn)等,需要的朋友可以參考下2019-07-07Springboot+MybatisPlus實(shí)現(xiàn)帶驗(yàn)證碼的登錄
本文主要介紹了Springboot+MybatisPlus實(shí)現(xiàn)帶驗(yàn)證碼的登錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼
這篇文章主要介紹了基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12Java實(shí)現(xiàn)上傳Excel文件并導(dǎo)入數(shù)據(jù)庫(kù)
這篇文章主要介紹了在java的基礎(chǔ)上學(xué)習(xí)上傳Excel文件并導(dǎo)出到數(shù)據(jù)庫(kù),感興趣的小伙伴不要錯(cuò)過(guò)奧2021-09-09spring boot中interceptor攔截器未生效的解決
這篇文章主要介紹了spring boot中interceptor攔截器未生效的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09