7.1、事務概述
1、什麼是事務
(1)事務是資料庫操作最基本單元,邏輯上一組操作,要麼都成功,如果有一個失敗,那麼所有操作都失敗
(2)典型場景:銀行轉賬
- Lucy轉賬100元給Mary
- Lucy少100元,Mary多100元
2、事務的四個特性(ACID)
(1)原子性
(2)一緻性
(3)隔離性
(4)持久性
7.2、搭建事務操作環境
1、建立資料庫表,添加記錄
2、建立
service
,搭建
DAO
,完成對象建立和注入關系
-
注入service
,在DAO
注入DAO
,在JdbcTemplate
注入JdbcTemplate
DataSource
【UserService.java】
@Service
public class UserService {
//注入DAO
@Autowired
private UserDAO userDAO;
}
【UserDAOImpl.java】
@Repository
public class UserDAOImpl implements UserDAO{
//注入JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
}
【bean1.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 開啟元件掃描 -->
<context:component-scan base-package="com.ssm"></context:component-scan>
<!-- 資料庫連接配接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///user_db" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<!--JdbcTemplate對象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
3、在
DAO
建立兩個方法:多錢和少錢的方法,在
service
建立轉賬的方法
【UserService.java】
@Service
public class UserService {
//注入DAO
@Autowired
private UserDAO userDAO;
public void accountMoney() {
//lucy少100
userDAO.reduceMoney();
//mary多100
userDAO.addMoney();
}
}
【UserDAOImpl.java】
@Repository
public class UserDAOImpl implements UserDAO{
//注入JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
//多錢
@Override
public void addMoney() {
String sql = "update t_account set money = money + ? where username = ?";
jdbcTemplate.update(sql, 100, "mary");
}
//lucy轉賬100給Mary
//少錢
@Override
public void reduceMoney() {
String sql = "update t_account set money = money - ? where username = ?";
jdbcTemplate.update(sql, 100, "lucy");
}
}
4、上面代碼,如果正常執行,沒有任何問題的,但是如果代碼執行過程中出現異常,有問題
@Service
public class UserService {
//注入DAO
@Autowired
private UserDAO userDAO;
public void accountMoney() {
//lucy少100
userDAO.reduceMoney();
//模拟異常
int i = 10/0;
//mary多100
userDAO.addMoney();
}
}
(1)上面的問題如何解決?
- 使用事務進行解決
(2)事務操作過程:
try {
//第一步:開啟事務
//第二步:進行事務操作
//lucy少100
userDAO.reduceMoney();
//模拟異常
int i = 10/0;
//mary多100
userDAO.addMoney();
//第三步:沒有發生異常,送出事務
} catch (Exception e) {
//第四步:出現異常,事務復原
}
7.3、Spring事務管理介紹
1、事務添加到
JavaEE
三層結構裡面
Service
層(業務邏輯層)
2、在
Spring
進行事務管理操作
- 有兩種方式:程式設計式事務管理和聲明式事務管理(使用)
3、聲明式事務管理
(1)基于注解方式(使用)
(2)基于xml配置檔案方式
4、在
Spring
進行聲明式事務管理,底層使用
AOP
5、
Spring
事務管理
API
(1)提供一個接口,代表事務管理器,這個接口針對不同的架構提供不同的實作類
7.4、聲明式事務管理(基于注解)
7.4.1、基于注解方式實作聲明式事務管理
1、在
Spring
配置檔案配置事務管理器
<!--建立事務管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入資料源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
2、在
Spring
配置檔案,開啟事務注解
(1)在
Spring
配置檔案引入名稱空間
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:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
(2)開啟事務注解
<!--開啟事務注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
3、在
Service
類上面(擷取
Service
類裡面方法上面)添加事務注解
(1)
@Transactional
,這個注解添加到類上面,也可以添加到方法上面
(2)如果把這個注解添加到類上面,這個類裡面所有的方法都添加事務
(3)如果把這個注解添加到方法上面,為這個方法添加事務
@Service
@Transactional
public class UserService {
}
7.4.2、聲明式事務管理參數配置
1、在
Service
類上面添加注解
@Transactional
,在這個注解裡面可以配置事務相關參數
2、
propagation
:事務傳播行為
(1)多事務方法直接進行調用,這個過程中事務是如何進行管理的
- 事務方法:對資料庫表資料進行變化的操作
-
架構事務傳播行為有7種:Spring
傳播屬性 描述 REQUIRED 如果有事務在運作,目前的方法就在這個事務内運作,否則,就啟動一個新的事務,并在自己的事務内運作 REQUIRED_NEW 目前的方法必須啟動新事務,并在它自己的事務内運作,如果有事務正在運作,應該将它挂起 SUPPORTS 如果有事務在運作,目前的方法就在這個事務内運作,否則它可以不運作在事務中 NOT_SUPPORTED 目前的方法不應該運作在事務中,如果有運作的事務,将它挂起 MANDATORY 目前的方法必須運作在事務内部,如果沒有正在運作的事務,就抛出異常 NEVER 目前的方法不應該運作在事務中,如果有運作的事務,就抛出異常 NESTED 如果有事務在運作,目前的方法就應該在這個事務的嵌套事務内運作,否則,就啟動一個新的事務,并在它自己的事務内運作
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {
}
3、
isolation
:事務隔離級别
(1)事務有特性稱為隔離性,多事務操作之間不會産生影響,不考慮隔離性産生很多問題
(2)有三個讀問題:髒讀、不可重複讀、虛讀(幻讀)
- 髒讀:一個未送出事務讀取到另一個未送出事務的資料
- 不可重複讀:一個未送出事務讀取到另一個送出事務修改資料
- 虛讀(幻讀):一個未送出事務讀取到另一個送出事務添加資料
(3)解決:通過設定事務隔離級别,解決讀問題
(4)4個隔離級别:
髒讀 | 不可重複讀 | 幻讀 | |
---|---|---|---|
READ UNCOMMITTED(讀未送出) | 有 | 有 | 有 |
READ COMMITTED(讀已送出) | 無 | 有 | 有 |
REPEATABLE READ(可重複讀) | 無 | 無 | 有 |
SERIALIZABLE(串行化) | 無 | 無 | 無 |
@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
public class UserService {
}
4、
timeout
:逾時時間
(1)事務需要在一定時間内進行送出,如果不送出進行復原
(2)預設值是-1,設定時間以秒機關進行計算
5、
readOnly
:是否隻讀
(1)讀:查詢操作;寫:添加修改删除操作
(2)
readOnly
預設值
false
,表示可以查詢,可以添加修改删除操作
(3)設定
readOnly
值是
true
,設定成
true
之後,隻能查詢
6、
rollbackFor
:復原
- 設定出現哪些異常進行事務復原
7、
noRollbackFor
:不復原
- 設定出現哪些異常不進行事務復原
7.5、聲明式事務管理(基于xml)
1、在
Spring
配置檔案中進行配置
- 第一步:配置事務管理器
<!--1.建立事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入資料源--> <property name="dataSource" ref="dataSource"></property> </bean>
- 第二步:配置通知
<!--2.配置通知--> <tx:advice id="txadvice"> <!--配置事務參數--> <tx:attributes> <!--指定哪種規則的方法上面添加事務--> <tx:method name="accountMoney" propagation="REQUIRED"/> <!--<tx:method name="account*"/>--> </tx:attributes> </tx:advice>
- 第三步:配置切入點和切面
<!--3.配置切入點和切面--> <aop:config> <!--配置切入點--> <aop:pointcut id="pt" expression="execution(* com.ssm.spring5.service.UserService.*(..))"/> <!--配置切面--> <aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor> </aop:config>
7.6、聲明式事務管理(完全注解開發)
1、建立配置類,使用配置類替代
xml
配置檔案
@Configuration//配置類
@ComponentScan(basePackages = "com.ssm")//元件掃描
@EnableTransactionManagement//開啟事務
public class TxConfig {
//建立資料庫連接配接池
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
//建立JdbcTemplate對象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
//到IOC容器中根據類型找到dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//建立事務管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
2、代碼測試
@Test
public void testAccount(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService userService = context.getBean("userService",UserService.class);
userService.accountMoney();
}