目錄
事務的概念
事務的概念(通俗理解):事務是數據庫操作最基本單元,邏輯上一組操作,要麼都成功,如果有一個失敗所有操作都失敗。
典型場景:銀行轉賬(這兩件事必須都成功或都不成功)
lucy 轉賬 100 元 給 mary
lucy 少 100,mary 多 100
事務四個特性(ACID)
(1)原子性:這個過程不可分割。
(2)一致性:操作之前和操作之後的總量不變。
(3)隔離性:多事務操作時不會相互參生影響。
(4)持久性:事務提交後數據庫數據會發生變化。
搭建事務操作的環境
創建數據庫表,添加記錄
代碼演示
(1)創建 service,搭建 dao,完成對象創建和注入關係。
(2)service 注入 dao,在 dao 注入 JdbcTemplate,在 配置文件中在JdbcTemplate 中注入 DataSource。
(3)在 dao 創建兩個方法:多錢和少錢的方法,在 service 創建方法(轉賬的方法)。
jdbc.properties:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/user_db?characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=18044229
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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.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">
<!--開啓組件掃描-->
<context:component-scan base-package="com.Keafmd"></context:component-scan>
<!--引入外部的屬性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置連接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}" ></property>
<property name="username" value="${jdbc.username}" ></property>
<property name ="password" value="${jdbc.password}" ></property>
</bean>
<!--創建jdbcTemplate對象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
UserDao 接口:
package com.Keafmd.spring5.dao;
/**
* Keafmd
*
* @ClassName: UserDao
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:09
*/
public interface UserDao {
//多錢
public void addMoney();
//少錢
public void reduceMoney();
}
實現類UserDaoImpl :
package com.Keafmd.spring5.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.rowset.JdbcRowSet;
/**
* Keafmd
*
* @ClassName: UserDaoImpl
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:09
*/
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
//少錢
@Override
public void reduceMoney() {
String sql = "update t_account set money =money-? where username =?";
jdbcTemplate.update(sql,100,"Lucy");
}
//多錢
@Override
public void addMoney() {
String sql = "update t_account set money =money+? where username =?";
jdbcTemplate.update(sql,100,"Mary");
}
}
UserService 類:
package com.Keafmd.spring5.service;
import com.Keafmd.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Keafmd
*
* @ClassName: UserService
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:08
*/
@Service
public class UserService {
//注入dao
@Autowired
private UserDao userDao;
//轉賬的方法
public void accountMoney(){
// Lucy 少100
userDao.reduceMoney();
//Mary多100
userDao.addMoney();
}
}
測試類:
package com.Keafmd.spring5.test;
import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Keafmd
*
* @ClassName: TestAccount
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:40
*/
public class TestAccount {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService",UserService.class);
userService.accountMoney();
}
}
測試前的數據:
測試後的數據:
這樣正常執行,沒有問題,但是如果中途出錯了呢?接着往下看。
事務場景引入
上面代碼,如果正常執行沒有問題的,但是如果代碼執行過程中出現異常,就會有問題,假如在Lucy少100後代碼發生了錯誤,那麼會怎樣?
我們手動添加個錯誤:
//轉賬的方法
public void accountMoney(){
// Lucy 少100
userDao.reduceMoney();
//手動添加異常
int i =100/0;
//Mary多100
userDao.addMoney();
}
這樣數據的變化就會出現問題。
測試前的數據:
測試後的數據:
這樣就發生了問題,Lucy少了100但是Mary卻沒有多。這就需要利用事務來解決,讓其在發生錯誤的時候進行回滾。
事務管理介紹
1、事務添加到 JavaEE 三層結構裏面 Service 層(業務邏輯層)
2、在 Spring 進行事務管理操作
有兩種方式:
(1)編程式事務管理(不方便)
(2)聲明式事務管理(使用)
3、聲明式事務管理
(1)基於註解方式(簡單方便)
(2)基於 xml 配置文件方式
4、在 Spring 進行聲明式事務管理,底層使用 AOP 原理
5、Spring 事務管理 API
提供一個接口,代表事務管理器,這個接口針對不同的框架提供不同的實現類:
Spring中使用的是DataSourceTransactionManager
註解聲明式事務管理
(1)在 spring 配置文件配置事務管理器
(2)在 spring 配置文件,開啓事務註解
(3)在 spring 配置文件引入名稱空間 tx
(4)開啓事務註解
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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.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">
<!--開啓組件掃描-->
<context:component-scan base-package="com.Keafmd"></context:component-scan>
<!--引入外部的屬性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置連接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}" ></property>
<property name="username" value="${jdbc.username}" ></property>
<property name ="password" value="${jdbc.password}" ></property>
</bean>
<!--創建jdbcTemplate對象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--創建事務管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入數據源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--開啓事務註解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
在 service 類上面(或者 service 類裏面方法上面)添加事務註解:
(1)@Transactional,這個註解添加到類上面,也可以添加方法上面
(2)如果把這個註解添加類上面,這個類裏面所有的方法都添加事務
(3)如果把這個註解添加方法上面,爲這個方法添加事務
UserService 類:
package com.Keafmd.spring5.service;
import com.Keafmd.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Keafmd
*
* @ClassName: UserService
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:08
*/
@Service
@Transactional // @Transactional,這個註解添加到類上面
public class UserService {
//注入dao
@Autowired
private UserDao userDao;
//轉賬的方法
public void accountMoney(){
// Lucy 少100
userDao.reduceMoney();
//手動添加異常,事務回滾
int i =100/0;
//Mary多100
userDao.addMoney();
}
}
現在我們添加事務後帶着異常運行測試類:
測試前的數據:
測試後的數據:
很明顯的看到測試後的數據沒有變化,是因爲發生了異常,進行了事務回滾,所以數據庫中的數據都沒有改變。
聲明式事務管理參數配置
在 service 類上面添加註解@Transactional,在這個註解裏面可以配置事務相關參數:
propagation:事務傳播行爲
事務傳播行爲:多事務方法直接進行調用,這個過程中事務 是如何進行管理的。
我們在add方法加了事務,update沒有加,當我們的add調用update的時候,事務會怎麼處理,這個過程就叫做事務的傳播行爲。有事務的方法調用沒事務的,還有就是都有事務並且調用這些情況發生的時候事務會怎麼處理,這些過程就叫做事務的傳播行爲。
事務的傳播行爲可以由傳播屬性指定。Spring 定義了7種類傳播行爲。
結合我們的例子介紹兩種最常見的:
默認的是REQUIRED:
@Transactional(propagation = Propagation.REQUIRED)
相當於:@Transactional
ioslation:事務隔離級別
(1)事務有特性成爲隔離性,多事務操作之間不會產生影響。不考慮隔離性產生很多問題
(2)有三個讀問題:髒讀、不可重複讀、虛(幻)讀
髒讀(致命問題):一個未提交事務讀取到另一個未提交事務的數據
不可重複讀(現象):一個未提交事務讀取到另一提交事務修改數據
虛讀(現象):一個未提交事務讀取到另一提交事務添加數據
不可重複讀的重點是修改了數據,同樣的條件 , 你讀取過的數據 , 再次讀取出來發現值不一樣了。
幻讀的重點是新增或者刪除了數據 , 第 1 次和第 2 次讀出來的記錄數不一樣。
解決:通過設置事務隔離級別,解決讀問題。
設置隔離級別方式:
@Transactional(isolation = Isolation.REPEATABLE_READ)
,這種可重複讀是mysql默認的設置方式。
timeout:超時時間
(1)事務需要在一定時間內進行提交,如果不提交進行回滾
(2)默認值是 -1 ,設置時間以秒單位進行計算
設置方式:@Transactional(timeout = 5)
readOnly:是否只讀
(1)讀:查詢操作,寫:添加修改刪除操作
(2)readOnly 默認值 false,表示可以查詢,可以添加修改刪除操作
(3)設置 readOnly 值是 true,設置成 true 之後,只能查詢
設置方式:@Transactional(readOnly = true)
rollbackFor:回滾
設置出現哪些異常進行事務回滾
設置方式:@Transactional(rollbackFor=Exception.class)
noRollbackFor:不回滾
設置出現哪些異常不進行事務回滾
設置方式:@Transactional(notRollbackFor=RunTimeException.class)
XML聲明式事務管理(不常用)
在 spring 配置文件中進行配置:
第一步:配置事務管理器
第二步:配置通知
第三步:配置切入點和切面
bean2.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.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">
<!--開啓組件掃描-->
<context:component-scan base-package="com.Keafmd"></context:component-scan>
<!--引入外部的屬性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置連接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}" ></property>
<property name="username" value="${jdbc.username}" ></property>
<property name ="password" value="${jdbc.password}" ></property>
</bean>
<!--創建jdbcTemplate對象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--創建事務管理器-->
<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.Keafmd.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
</beans>
把UserService的@Transactional註解註釋掉,其它不變,新建個測試類:
package com.Keafmd.spring5.test;
import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Keafmd
*
* @ClassName: TestAccount
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:40
*/
public class TestAccount {
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
UserService userService = context.getBean("userService",UserService.class);
userService.accountMoney();
}
}
這樣我們使用的是bean2.xml配置文件,那我們這就是XML聲明式事務管理。
完全註解聲明式事務管理
在註解聲明式事務管理我們也是需要使用bean1.xml配置文件,我們也可以不使用配置文件,創建個配置類,和註解聲明式事務管理相比其它類都不變。
TxConfig類:
package com.Keafmd.spring5.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* Keafmd
*
* @ClassName: TxConfig
* @Description: 完全註解開發
* @author: 牛哄哄的柯南
* @date: 2021-01-20 21:16
*/
@Configuration //配置類
@ComponentScan(basePackages = "com.Keafmd") //組件掃描
@EnableTransactionManagement // 開啓事務
public class TxConfig {
//創建數據庫連接池
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/user_db?characterEncoding=utf8&useUnicode=true&useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("18044229");
return dataSource;
}
//創建jdbcTemplate對象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//創建事務管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
測試類:
package com.Keafmd.spring5.test;
import com.Keafmd.spring5.config.TxConfig;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Keafmd
*
* @ClassName: TestAccount
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-01-20 10:40
*/
public class TestAccount {
//使用配置類
@Test
public void test3(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService userService = context.getBean("userService",UserService.class);
userService.accountMoney();
}
}
這樣我們就實現了完全註解聲明式事務管理。