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ù)不回滾。沒有默認(rèn)值。表示任何異常都回滾。
- no-rollback-for: 用于指定一個(gè)異常,當(dāng)產(chǎn)生該異常時(shí),事務(wù)不回滾,產(chǎn)生其他異常時(shí),事務(wù)回滾。沒有默認(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)文章
RxJava2 Scheduler使用實(shí)例深入解析
這篇文章主要為大家介紹了RxJava2 Scheduler使用實(shí)例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
深入解析Spring Cloud內(nèi)置的Zuul過濾器
這篇文章主要給大家深入的介紹了Spring Cloud內(nèi)置的Zuul過濾器的相關(guān)資料,文中給大家介紹的很詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-02-02
Java 超詳細(xì)講解數(shù)據(jù)結(jié)構(gòu)的應(yīng)用
數(shù)據(jù)結(jié)構(gòu)是計(jì)算機(jī)存儲(chǔ)、組織數(shù)據(jù)的方式。數(shù)據(jù)結(jié)構(gòu)是指相互之間存在一種或多種特定關(guān)系的數(shù)據(jù)元素的集合,讓我們一起來了解數(shù)據(jù)結(jié)構(gòu)是如何應(yīng)用的2022-04-04
Servlet編程第一步之從零構(gòu)建Hello?World應(yīng)用詳細(xì)步驟+圖解
本文詳細(xì)介紹了Servlet和maven的基本概念及其在JavaWeb開發(fā)中的應(yīng)用,首先解釋了Servlet是一個(gè)在服務(wù)器上處理請(qǐng)求的Java程序,然后介紹了maven作為管理和構(gòu)建Java項(xiàng)目的工具,需要的朋友可以參考下2024-10-10
Java組件FileUpload上傳文件實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Java組件FileUpload上傳文件實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
詳解springboot設(shè)置默認(rèn)參數(shù)Springboot.setDefaultProperties(map)不生效解決
這篇文章主要介紹了詳解springboot設(shè)置默認(rèn)參數(shù)Springboot.setDefaultProperties(map)不生效解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

