Java_Spring之Spring 中的事務(wù)控制
更新時間:2023年04月06日 09:21:09 作者:JiangTao_xlili
這篇文章主要介紹了Java Spring中的事務(wù)控制,事務(wù)控制要明確內(nèi)容,事務(wù)的控制都是基于AOP的,感興趣的小伙伴可以參考閱讀本文
1 Spring 事務(wù)控制要明確的內(nèi)容
- 第一:JavaEE 體系進行分層開發(fā),事務(wù)處理位于業(yè)務(wù)層,Spring 提供了分層設(shè)計業(yè)務(wù)層的事務(wù)處理解決方案。
- 第二:spring 框架提供了一組事務(wù)控制的接口。具體在后面的第二小節(jié)介紹。這組接口是在spring-tx-5.0.2.RELEASE.jar 中。
- 第三:spring 的事務(wù)控制都是基于 AOP 的,它既可以使用編程的方式實現(xiàn),也可以使用配置的方式實現(xiàn)。學習的重點是使用配置的方式實現(xiàn)。
2 Spring 中事務(wù)控制的 API 介紹
2.1 PlatformTransactionManager
此接口是 spring 的事務(wù)管理器,它里面提供了我們常用的操作事務(wù)的方法,如下圖
- 在開發(fā)中都是使用它的實現(xiàn)類,如下圖:
- 真正管理事務(wù)的對象
- org.springframework.jdbc.datasource.DataSourceTransactionManager
- 使用 Spring JDBC 或 iBatis 進行持久化數(shù)據(jù)時使用
- org.springframework.orm.hibernate5.HibernateTransactionManager使用
- Hibernate 版本進行持久化數(shù)據(jù)時使用
- org.springframework.jdbc.datasource.DataSourceTransactionManager
- 真正管理事務(wù)的對象
2.2 TransactionDefinition
事務(wù)的定義信息對象,里面有如下方法
2.2.1 事務(wù)的隔離級別
2.2.2 事務(wù)的傳播行為
- REQUIRED:如果當前沒有事務(wù),就新建一個事務(wù),如果已經(jīng)存在一個事務(wù)中,加入到這個事務(wù)中。一般的選擇(默認值)
- SUPPORTS:支持當前事務(wù),如果當前沒有事務(wù),就以非事務(wù)方式執(zhí)行(沒有事務(wù))
- MANDATORY:使用當前的事務(wù),如果當前沒有事務(wù),就拋出異常
- REQUERS_NEW:新建事務(wù),如果當前在事務(wù)中,把當前事務(wù)掛起。
- NOT_SUPPORTED:以非事務(wù)方式執(zhí)行操作,如果當前存在事務(wù),就把當前事務(wù)掛起
- NEVER:以非事務(wù)方式運行,如果當前存在事務(wù),拋出異常
- NESTED:如果當前存在事務(wù),則在嵌套事務(wù)內(nèi)執(zhí)行。如果當前沒有事務(wù),則執(zhí)行 REQUIRED 類似的操作。
2.2.3 超時時間
- 默認值是-1,沒有超時限制。如果有,以秒為單位進行設(shè)置。
2.2.4 是否是只讀事務(wù)
- 建議查詢時設(shè)置為只讀。
2.3 TransactionStatus
- 此接口提供的是事務(wù)具體的運行狀態(tài),方法介紹如下圖:
3 基于 XML 的聲明式事務(wù)控制(配置方式)
3.1 環(huán)境搭建
3.1.1 第一步:拷貝必要的 jar 包到工程的 lib 目錄
3.1.2 第二步:創(chuàng)建 spring 的配置文件并導入約束
- 此處需要導入 aop 和 tx 兩個名稱空間
<?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 第三步:準備數(shù)據(jù)庫表和實體類
- 創(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;
- 賬戶的實體
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ù)層接口和實現(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ù)層實現(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ù)名稱查詢兩個賬戶 Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targeName); //2.修改兩個賬戶的金額 source.setMoney(source.getMoney()-money);//轉(zhuǎn)出賬戶減錢 target.setMoney(target.getMoney()+money);//轉(zhuǎn)入賬戶加錢 //3.更新兩個賬戶 accountDao.updateAccount(source); int i=1/0; accountDao.updateAccount(target); } }
3.1.5 第五步:編寫 Dao 接口和實現(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); }
- 賬戶的持久層實現(xiàn)類
- 此版本 dao,只需要給它的父類注入一個數(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é)果集不唯一,不是只有一個賬戶對象"); } return list.get(0); } @Override public void updateAccount(Account account) { getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId()); } }
- 賬戶的封裝類 RowMapper 的實現(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ù)層和持久層對
<!-- 配置 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ù)管理器
<!-- 配置一個事務(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 標簽內(nèi)部 配置事務(wù)的屬性 --> <tx:attributes> <!-- 指定方法名稱:是業(yè)務(wù)核心方法 read-only:是否是只讀事務(wù)。默認 false,不只讀。 isolation:指定事務(wù)的隔離級別。默認值是使用數(shù)據(jù)庫的默認隔離級別。 propagation:指定事務(wù)的傳播行為。 timeout:指定超時時間。默認值為:-1。永不超時。 rollback-for:用于指定一個異常,當執(zhí)行產(chǎn)生該異常時,事務(wù)回滾。產(chǎn)生其他異常,事務(wù)不回滾。沒有默認值,任何異常都回滾。 no-rollback-for:用于指定一個異常,當產(chǎn)生該異常時,事務(wù)不回滾,產(chǎn)生其他異常時,事務(wù)回滾。沒有默認值,任何異常都回滾。 --> <tx:method name="*" read-only="false" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> </tx:attributes>
3.2.4 第四步:配置 AOP 切入點表達式
<!-- 配置 aop --> <aop:config> <!-- 配置切入點表達式 --> <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/> </aop:config>
3.2.5 第五步:配置切入點表達式和事務(wù)通知的對應(yīng)關(guān)系
<!-- 在 aop:config 標簽內(nèi)部:建立事務(wù)的通知和切入點表達式的關(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 的配置文件導入約束并配置掃描的包
<?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)建容器時要掃描的包 --> <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ù)庫表和實體類
和基于 xml 的配置相同。略
4.1.4 第四步:創(chuàng)建業(yè)務(wù)層接口和實現(xiàn)類并使用注解讓 spring 管理
賬戶的業(yè)務(wù)層實現(xiàn)類
@Service("accountService")public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; //其余代碼和基于 XML 的配置相同}
4.1.5 第五步:創(chuàng)建 Dao 接口和實現(xiàn)類并使用注解讓 spring 管理
賬戶的持久層實現(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)接口上,表示該接口的所有實現(xiàn)類都有事務(wù)支持。
- 出現(xiàn)在類上,表示類中所有方法有事務(wù)支持。
- 出現(xiàn)在方法上,表示方法有事務(wù)支持。
- 以上三個位置的優(yōu)先級:方法>類>接口
@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ù)名稱查詢兩個賬戶 Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targeName); //2.修改兩個賬戶的金額 source.setMoney(source.getMoney()-money);//轉(zhuǎn)出賬戶減錢 target.setMoney(target.getMoney()+money);//轉(zhuǎn)入賬戶加錢 //3.更新兩個賬戶 accountDao.updateAccount(source); //int i=1/0; accountDao.updateAccount(target); }}
4.2.3 第三步:在配置文件中開啟 spring 對注解事務(wù)的支持
<!-- 開啟 spring 對注解事務(wù)的支持 --><tx:annotation-driven transaction-manager="transactionManager"/>
4.3 不使用 xml 的配置方式
@Configuration@EnableTransactionManagementpublic class SpringTxConfiguration { //里面配置數(shù)據(jù)源,配置 JdbcTemplate,配置事務(wù)管理器。在之前的步驟已經(jīng)寫過了。}
以上就是Java_Spring之Spring 中的事務(wù)控制的詳細內(nèi)容,更多關(guān)于Java Spring事務(wù)控制的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java 多線程等待優(yōu)雅的實現(xiàn)方式之Phaser同步屏障
在JAVA 1.7引入了一個新的并發(fā)API:Phaser,一個可重用的同步barrier。在此前,JAVA已經(jīng)有CyclicBarrier、CountDownLatch這兩種同步barrier,但是Phaser更加靈活,而且側(cè)重于 重用2021-11-11Maven pom.xml 添加本地jar包依賴以及打包方法
這篇文章主要介紹了Maven pom.xml 添加本地jar包依賴以及打包方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09