寫在前面: 本文將告訴你:數據庫事務,以及如何使用Spring整理事務,以及用註解開發事務。 作者是一個學生,沒有能力寫得太深,需要的可以去看看大佬們的 手撕Spring源碼。
如果對你有幫助可以點贊支持一下^ _ ^
作者公衆號:小白編碼
數據庫事務介紹
-
事務:一組邏輯操作單元,使數據從一種狀態變換到另一種狀態。
-
事務處理(事務操作):保證所有事務都作爲一個工作單元來執行,即使出現了故障,都不能改變這種執行方式。當在一個事務中執行多個操作時,要麼所有的事務都被提交(commit),那麼這些修改就永久地保存下來;要麼數據庫管理系統將放棄所作的所有修改,整個事務**回滾(rollback)**到最初狀態。
-
爲確保數據庫中數據的一致性,數據的操縱應當是離散的成組的邏輯單元:當它全部完成時,數據的一致性可以保持,而當這個單元中的一部分操作失敗,整個事務應全部視爲錯誤,所有從起始點以後的操作應全部回退到開始狀態。
事務的ACID屬性
-
原子性(Atomicity)
原子性是指事務是一個不可分割的工作單位,事務中的操作要麼都發生,要麼都不發生。 -
一致性(Consistency)
事務必須使數據庫從一個一致性狀態變換到另外一個一致性狀態。 -
隔離性(Isolation)
事務的隔離性是指一個事務的執行不能被其他事務干擾,即一個事務內部的操作及使用的數據對併發的其他事務是隔離的,併發執行的各個事務之間不能互相干擾。 -
持久性(Durability)
持久性是指一個事務一旦被提交,它對數據庫中數據的改變就是永久性的,接下來的其他操作和數據庫故障不應該對其有任何影響。
數據庫的併發問題
-
對於同時運行的多個事務, 當這些事務訪問數據庫中相同的數據時, 如果沒有采取必要的隔離機制, 就會導致各種併發問題:
- 髒讀: 對於兩個事務 T1, T2, T1 讀取了已經被 T2 更新但還沒有被提交的字段。之後, 若 T2 回滾, T1讀取的內容就是臨時且無效的。
- 不可重複讀: 對於兩個事務T1, T2, T1 讀取了一個字段, 然後 T2 更新了該字段。之後, T1再次讀取同一個字段, 值就不同了。
- 幻讀: 對於兩個事務T1, T2, T1 從一個表中讀取了一個字段, 然後 T2 在該表中插入了一些新的行。之後, 如果 T1 再次讀取同一個表, 就會多出幾行。
-
數據庫事務的隔離性: 數據庫系統必須具有隔離併發運行各個事務的能力, 使它們不會相互影響, 避免各種併發問題。
-
一個事務與其他事務隔離的程度稱爲隔離級別。數據庫規定了多種事務隔離級別, 不同隔離級別對應不同的干擾程度, 隔離級別越高, 數據一致性就越好, 但併發性越弱。
四種隔離級別
-
數據庫提供的4種事務隔離級別:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-m7zu5UHE-1590579555991)(C:/Users/JUN/Desktop/生產力工具/筆記/JDBC/尚硅谷_宋紅康_JDBC.assets/1555586275271.png)]
-
Oracle 支持的 2 種事務隔離級別:READ COMMITED, SERIALIZABLE。 Oracle 默認的事務隔離級別爲: READ COMMITED 。
-
Mysql 支持 4 種事務隔離級別。Mysql 默認的事務隔離級別爲: REPEATABLE READ。
Spring事務控制
事務的傳播行爲:
REQUIRED:如果當前沒有事務,就新建一個事務,如果已經存在一個事務中,加入到這個事務中。一般的選擇(默認值)
SUPPORTS:支持當前事務,如果當前沒有事務,就以非事務方式執行(沒有事務)
MANDATORY:使用當前的事務,如果當前沒有事務,就拋出異常 REQUERS_NEW:新建事務,如果當前在事務中,把當前事務掛起。
NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起
NEVER:以非事務方式運行,如果當前存在事務,拋出異常
NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行REQUIRED類似的操作。
設置超時時間默認是沒有超時限制,默認值是-1,以秒爲單位.
查詢的時候設爲只讀
基於xml配置事務控制
spring中基於XML的聲明式事務控制配置步驟
1、配置事務管理器
2、配置事務的通知
此時我們需要導入事務的約束 tx名稱空間和約束,同時也需要aop的
使用tx:advice標籤配置事務通知
屬性:
id:給事務通知起一個唯一標識
transaction-manager:給事務通知提供一個事務管理器引用
3、配置AOP中的通用切入點表達式
4、建立事務通知和切入點表達式的對應關係
5、配置事務的屬性
是在事務的通知tx:advice標籤的內部
配置事務的屬性
isolation: 用於指定事務的隔離級別。默認值是DEFAULT,表示使用數據庫的默認隔離級別。
propagation: 用於指定事務的傳播行爲。默認值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以選擇SUPPORTS。
read-only: 用於指定事務是否只讀。只有查詢方法才能設置爲true。默認值是false,表示讀寫。
timeout: 用於指定事務的超時時間,默認值是-1,表示永不超時。如果指定了數值,以秒爲單位。
rollback-for: 用於指定一個異常,當產生該異常時,事務回滾,產生其他異常時,事務不回滾。沒有默認值。表示任何異常都回滾。
no-rollback-for: 用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時事務回滾。沒有默認值。表示任何異常都回滾。
依賴注入:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
環境搭建:
Account表:
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) DEFAULT NULL,
`money` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
對應javaBean:
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
}
Dao:自行編寫接口
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
//判斷是否空,如果空返回null,如果非空返回指定id的
return accounts.isEmpty() ? null : accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<>(Account.class), accountName);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("結果集不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
}
}
Service:
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
//2.1根據名稱查詢轉出賬戶
Account source = accountDao.findAccountByName(sourceName);
//2.2根據名稱查詢轉入賬戶
Account target = accountDao.findAccountByName(targetName);
//2.3轉出賬戶減錢
source.setMoney(source.getMoney()-money);
//2.4轉入賬戶加錢
target.setMoney(target.getMoney()+money);
//2.5更新轉出賬戶
accountDao.updateAccount(source);
// int i=1/0;
//2.6更新轉入賬戶
accountDao.updateAccount(target);
}
}
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: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">
<!-- 配置業務層-->
<bean id="accountService" class="cn.codewhite.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置賬戶的持久層-->
<bean id="accountDao" class="cn.codewhite.dao.impl.AccountDaoImpl">
</bean>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源-->
<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:2001/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="20010303"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"> </property>
</bean>
<!-- 配置事務的通知 id可以隨便寫。-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 配置事務的屬性-->
<!-- 爲連接點指定事務屬性,指定方法 -->
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入點表達式-->
<aop:pointcut id="pt1" expression="execution(* cn.codewhite.service.impl.*.*(..))"/>
<!--建立切入點表達式和事務通知的對應關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
測試方法:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountDaoTest {
@Autowired
AccountService as;
@Test
public void test() {
as.transfer("tom","jack",100f);
}
}
基於註解配置事務控制
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:aop="http://www.springframework.org/schema/aop"
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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring創建容器時要掃描的包-->
<context:component-scan base-package="cn.codewhite"></context:component-scan>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源-->
<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:2001/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="20010303"></property>
</bean>
<!-- spring中基於註解 的聲明式事務控制配置步驟
1、配置事務管理器
2、開啓spring對註解事務的支持
3、在需要事務支持的地方使用@Transactional註解
-->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 開啓spring對註解事務的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
運行環境:在xml的基礎上:
ServiceImpl配置:
accountDao:
測試類:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountDaoTest {
@Autowired
@Qualifier("accountService")
private AccountService as;
@Test
public void test() {
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
as.transfer("tom","jack",100f);
}
}
運行:轉賬成功:
此時我在Service中加入除零異常:
測試結果:
數據庫回滾成功!
寫在後邊:
寫得不好,請見諒,如果需要PDF版的可以找我。