你瞭解Spring事物控制特性嗎

1、事務特性

原子性:強調事務的不可分割 一致性:強調的是事務的執行的先後,數據的完整性要保持一致 隔離性:一個事務的執行不該該受到其餘事務的干擾 持久性:事務一旦結束(提交/回滾)數據就持久保持到了數據庫數據庫

2、若是不考慮隔離性,會引起一些安全性問題

讀問題
複製代碼

髒讀:一個事務讀到另外一個事務尚未提交的數據 不可重複讀:一個事務讀到了另外一個事務已經提交的update數據,致使在當前的事務中屢次查詢數據不一致 虛讀/幻讀:一個事務讀到另外一個事務已經insert數據,致使當前事務中屢次查詢結果不一致安全

寫問題
複製代碼

引起兩類丟失更新bash

3、解決引起的讀問題
設置事務的隔離級別 read uncommitted :未提交讀。髒讀,不可重複讀,虛讀均可能發生 read committed :已提交讀。避免髒讀,不可重複讀和虛度有可能發生 repeatable read :可重複讀。避免髒讀和不可重複讀,虛讀可能發生 serializable :串行化的。避免髒讀,不可重複讀,虛讀的發生session

select @@tx_isolation; 查看隔離級別
set session transaction isolation level 級別; 設置隔離級別
複製代碼

4、演示讀問題

演示髒讀
複製代碼

1.分別開啓兩個dos窗口 A.B 2.先查看兩個窗口的隔離級別 select @@tx_isolation; 3.設置A窗口的隔離級別爲未提交讀ui

set session transaction isolation level read uncommitted;
複製代碼

4.分別在兩個窗口開啓事務spa

start transaction;
複製代碼

5.分別開啓兩個dos窗口 A.Bcode

update account set money = money - 1000 where name = '張森';
update account set money = money + 1000 where name = '鳳姐';
複製代碼

6.在A窗口查詢數據select * from account; -- A事務讀到了B事務尚未提交的數據;事務

演示避免髒讀,演示不可重複讀發送
複製代碼

1.分別開兩個窗口,A.B 2.設置A窗口的隔離級別:read committedstring

set session transaction isolation level read committed;
複製代碼

3.分別在兩個窗口開啓事務 start transaction; 4.在B窗口完成轉帳it

update account set money = money - 1000 where name = '張森';
update account set money = money + 1000 where name = '鳳姐';
複製代碼

5.在A窗口進行查詢

select * from account; -- 避免髒讀
複製代碼

6.在B窗口提交事務

commit;
複製代碼

7.在A窗口中再次查詢

select * from account;  轉帳成功.(不可重複讀:一個事務讀到另外一個事務中已經提交的update的數據,致使屢次查詢結果不一致.)
複製代碼
避免髒讀和不可重複讀,演示虛讀
複製代碼

1.分別開啓兩個窗口,A.B 2.設置A窗口的隔離級別: repeatable read

set session transaction isolation level repeatable read;
複製代碼

3.分別在兩個窗口中開啓事務

start transaction;
複製代碼

4.在B窗口完成轉帳的操做

update account set money = money - 1000 where name = '張森';
update account set money = money + 1000 where name = '鳳姐';
複製代碼

5.在A窗口查詢

select * from account; -- 轉帳沒有成功:避免髒讀.
複製代碼

6.在B窗口提交事務

commit;
複製代碼

7.在A窗口再次查詢

select * from account; -- 轉帳沒有成功:避免不可重複讀.
複製代碼
避免虛讀
複製代碼

1.分別開啓兩個窗口,A.B 2.設置A窗口的隔離級別:repeatable read

set session transaction isolation level repeatable read;

複製代碼

3.分別在兩個窗口中開啓事務

start transaction;
複製代碼

4.在B窗口完成插入操做

insert into account values (null,'王老師',10000)
複製代碼

5.在A中進行查詢操做

select * from account; -- 沒有查詢到任何結果
複製代碼

6.在B窗口提交事務

commit; -- A窗口立刻就會顯示數據
複製代碼
相關文章
相關標籤/搜索