Java_Spring之Spring 中的事務(wù)控制
1 Spring 事務(wù)控制要明確的內(nèi)容
- 第一:JavaEE 體系進(jìn)行分層開發(fā),事務(wù)處理位于業(yè)務(wù)層,Spring 提供了分層設(shè)計(jì)業(yè)務(wù)層的事務(wù)處理解決方案。
- 第二:spring 框架提供了一組事務(wù)控制的接口。具體在后面的第二小節(jié)介紹。這組接口是在spring-tx-5.0.2.RELEASE.jar 中。
- 第三:spring 的事務(wù)控制都是基于 AOP 的,它既可以使用編程的方式實(shí)現(xiàn),也可以使用配置的方式實(shí)現(xiàn)。學(xué)習(xí)的重點(diǎn)是使用配置的方式實(shí)現(xiàn)。
2 Spring 中事務(wù)控制的 API 介紹
2.1 PlatformTransactionManager
此接口是 spring 的事務(wù)管理器,它里面提供了我們常用的操作事務(wù)的方法,如下圖

- 在開發(fā)中都是使用它的實(shí)現(xiàn)類,如下圖:
- 真正管理事務(wù)的對(duì)象
- org.springframework.jdbc.datasource.DataSourceTransactionManager
- 使用 Spring JDBC 或 iBatis 進(jìn)行持久化數(shù)據(jù)時(shí)使用
- org.springframework.orm.hibernate5.HibernateTransactionManager使用
- Hibernate 版本進(jìn)行持久化數(shù)據(jù)時(shí)使用
- org.springframework.jdbc.datasource.DataSourceTransactionManager
- 真正管理事務(wù)的對(duì)象
2.2 TransactionDefinition
事務(wù)的定義信息對(duì)象,里面有如下方法

2.2.1 事務(wù)的隔離級(jí)別

2.2.2 事務(wù)的傳播行為
- REQUIRED:如果當(dāng)前沒有事務(wù),就新建一個(gè)事務(wù),如果已經(jīng)存在一個(gè)事務(wù)中,加入到這個(gè)事務(wù)中。一般的選擇(默認(rèn)值)
- SUPPORTS:支持當(dāng)前事務(wù),如果當(dāng)前沒有事務(wù),就以非事務(wù)方式執(zhí)行(沒有事務(wù))
- MANDATORY:使用當(dāng)前的事務(wù),如果當(dāng)前沒有事務(wù),就拋出異常
- REQUERS_NEW:新建事務(wù),如果當(dāng)前在事務(wù)中,把當(dāng)前事務(wù)掛起。
- NOT_SUPPORTED:以非事務(wù)方式執(zhí)行操作,如果當(dāng)前存在事務(wù),就把當(dāng)前事務(wù)掛起
- NEVER:以非事務(wù)方式運(yùn)行,如果當(dāng)前存在事務(wù),拋出異常
- NESTED:如果當(dāng)前存在事務(wù),則在嵌套事務(wù)內(nèi)執(zhí)行。如果當(dāng)前沒有事務(wù),則執(zhí)行 REQUIRED 類似的操作。
2.2.3 超時(shí)時(shí)間
- 默認(rèn)值是-1,沒有超時(shí)限制。如果有,以秒為單位進(jìn)行設(shè)置。
2.2.4 是否是只讀事務(wù)
- 建議查詢時(shí)設(shè)置為只讀。
2.3 TransactionStatus
- 此接口提供的是事務(wù)具體的運(yùn)行狀態(tài),方法介紹如下圖:

3 基于 XML 的聲明式事務(wù)控制(配置方式)
3.1 環(huán)境搭建
3.1.1 第一步:拷貝必要的 jar 包到工程的 lib 目錄

3.1.2 第二步:創(chuàng)建 spring 的配置文件并導(dǎo)入約束
- 此處需要導(dǎo)入 aop 和 tx 兩個(gè)名稱空間
<?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"></beans>
3.1.3 第三步:準(zhǔn)備數(shù)據(jù)庫表和實(shí)體類
- 創(chuàng)建數(shù)據(jù)庫:
create database spring_day04;use spring_day04;
- 創(chuàng)建表:
create table account( id int primary key auto_increment, name varchar(40), money float) character set utf8 collate utf8_general_ci;
- 賬戶的實(shí)體
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}3.1.4 第四步:編寫業(yè)務(wù)層接口和實(shí)現(xiàn)類 賬戶的業(yè)務(wù)層接口
public interface IAccountService {
/**
* 根據(jù) id 查詢賬戶信息
* @param id
* @return
*/
Account findAccountById(Integer id);//查
/**
* 轉(zhuǎn)賬
* @param sourceName 轉(zhuǎn)出賬戶名稱
* @param targeName 轉(zhuǎn)入賬戶名稱
* @param money 轉(zhuǎn)賬金額
*/
void transfer(String sourceName,String targeName,Float money);//增刪改
}- 賬戶的業(yè)務(wù)層實(shí)現(xiàn)類
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根據(jù)名稱查詢兩個(gè)賬戶
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改兩個(gè)賬戶的金額
source.setMoney(source.getMoney()-money);//轉(zhuǎn)出賬戶減錢
target.setMoney(target.getMoney()+money);//轉(zhuǎn)入賬戶加錢
//3.更新兩個(gè)賬戶
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}3.1.5 第五步:編寫 Dao 接口和實(shí)現(xiàn)類
- 賬戶的持久層接口
public interface IAccountDao {
/**
* 根據(jù) id 查詢賬戶信息
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根據(jù)名稱查詢賬戶信息
* @return
*/
Account findAccountByName(String name);
/**
* 更新賬戶信息
* @param account
*/
void updateAccount(Account account);
}- 賬戶的持久層實(shí)現(xiàn)類
- 此版本 dao,只需要給它的父類注入一個(gè)數(shù)據(jù)源
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("結(jié)果集不唯一,不是只有一個(gè)賬戶對(duì)象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}- 賬戶的封裝類 RowMapper 的實(shí)現(xiàn)類
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}3.1.6 第六步:在配置文件中配置業(yè)務(wù)層和持久層對(duì)
<!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!-- 注入 dataSource -->
<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:///spring_day04"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>3.2 配置步驟
3.2.1 第一步:配置事務(wù)管理器
<!-- 配置一個(gè)事務(wù)管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入 DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>3.2.2 第二步:配置事務(wù)的通知引用事務(wù)管理器
<!-- 事務(wù)的配置 --><tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
3.2.3 第三步:配置事務(wù)的屬性
<!--在 tx:advice 標(biāo)簽內(nèi)部 配置事務(wù)的屬性 -->
<tx:attributes>
<!-- 指定方法名稱:是業(yè)務(wù)核心方法
read-only:是否是只讀事務(wù)。默認(rèn) false,不只讀。
isolation:指定事務(wù)的隔離級(jí)別。默認(rèn)值是使用數(shù)據(jù)庫的默認(rèn)隔離級(jí)別。
propagation:指定事務(wù)的傳播行為。
timeout:指定超時(shí)時(shí)間。默認(rèn)值為:-1。永不超時(shí)。
rollback-for:用于指定一個(gè)異常,當(dāng)執(zhí)行產(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)值,任何異常都回滾。
-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>3.2.4 第四步:配置 AOP 切入點(diǎn)表達(dá)式
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入點(diǎn)表達(dá)式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
</aop:config>3.2.5 第五步:配置切入點(diǎn)表達(dá)式和事務(wù)通知的對(duì)應(yīng)關(guān)系
<!-- 在 aop:config 標(biāo)簽內(nèi)部:建立事務(wù)的通知和切入點(diǎn)表達(dá)式的關(guān)系 --><aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
4 基于注解的配置方式
4.1 環(huán)境搭建
4.1.1 第一步:拷貝必備的 jar 包到工程的 lib 目錄

4.1.2 第二步:創(chuàng)建 spring 的配置文件導(dǎo)入約束并配置掃描的包
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置 spring 創(chuàng)建容器時(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>
<!-- 配置 spring 提供的內(nèi)置數(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/spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>4.1.3 第三步:創(chuàng)建數(shù)據(jù)庫表和實(shí)體類
和基于 xml 的配置相同。略
4.1.4 第四步:創(chuàng)建業(yè)務(wù)層接口和實(shí)現(xiàn)類并使用注解讓 spring 管理
賬戶的業(yè)務(wù)層實(shí)現(xiàn)類
@Service("accountService")public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; //其余代碼和基于 XML 的配置相同}4.1.5 第五步:創(chuàng)建 Dao 接口和實(shí)現(xiàn)類并使用注解讓 spring 管理
賬戶的持久層實(shí)現(xiàn)類
@Repository("accountDao")public class AccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; //其余代碼和基于 XML 的配置相同}4.2 配置步驟
4.2.1 第一步:配置事務(wù)管理器并注入數(shù)據(jù)源
<!-- 配置事務(wù)管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property></bean>
4.2.2 第二步:在業(yè)務(wù)層使用@Transactional 注解
- 該注解的屬性和 xml 中的屬性含義一致。該注解可以出現(xiàn)在接口上,類上和方法上。
- 出現(xiàn)接口上,表示該接口的所有實(shí)現(xiàn)類都有事務(wù)支持。
- 出現(xiàn)在類上,表示類中所有方法有事務(wù)支持。
- 出現(xiàn)在方法上,表示方法有事務(wù)支持。
- 以上三個(gè)位置的優(yōu)先級(jí):方法>類>接口
@Service("accountService")@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public Account findAccountById(Integer id) { return accountDao.findAccountById(id); } @Override @Transactional(readOnly=false,propagation=Propagation.REQUIRED) public void transfer(String sourceName, String targeName, Float money) { //1.根據(jù)名稱查詢兩個(gè)賬戶 Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targeName); //2.修改兩個(gè)賬戶的金額 source.setMoney(source.getMoney()-money);//轉(zhuǎn)出賬戶減錢 target.setMoney(target.getMoney()+money);//轉(zhuǎn)入賬戶加錢 //3.更新兩個(gè)賬戶 accountDao.updateAccount(source); //int i=1/0; accountDao.updateAccount(target); }}4.2.3 第三步:在配置文件中開啟 spring 對(duì)注解事務(wù)的支持
<!-- 開啟 spring 對(duì)注解事務(wù)的支持 --><tx:annotation-driven transaction-manager="transactionManager"/>
4.3 不使用 xml 的配置方式
@Configuration@EnableTransactionManagementpublic class SpringTxConfiguration { //里面配置數(shù)據(jù)源,配置 JdbcTemplate,配置事務(wù)管理器。在之前的步驟已經(jīng)寫過了。}以上就是Java_Spring之Spring 中的事務(wù)控制的詳細(xì)內(nèi)容,更多關(guān)于Java Spring事務(wù)控制的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java 多線程等待優(yōu)雅的實(shí)現(xiàn)方式之Phaser同步屏障
在JAVA 1.7引入了一個(gè)新的并發(fā)API:Phaser,一個(gè)可重用的同步barrier。在此前,JAVA已經(jīng)有CyclicBarrier、CountDownLatch這兩種同步barrier,但是Phaser更加靈活,而且側(cè)重于 重用2021-11-11
Java實(shí)現(xiàn)的簡(jiǎn)單音樂播放器功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)的簡(jiǎn)單音樂播放器功能,涉及java針對(duì)多媒體文件相關(guān)載入、播放相關(guān)操作技巧,需要的朋友可以參考下2019-02-02
教你用Java在個(gè)人電腦上實(shí)現(xiàn)微信掃碼支付
今天給大家?guī)淼氖荍ava實(shí)戰(zhàn)的相關(guān)知識(shí),文章圍繞著Java在個(gè)人電腦上實(shí)現(xiàn)微信掃碼支付展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Maven pom.xml 添加本地jar包依賴以及打包方法
這篇文章主要介紹了Maven pom.xml 添加本地jar包依賴以及打包方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

