上一篇博文《SSM三大框架整合詳細教程》詳細說了如何整合Spring、SpringMVC和MyBatis這三大框架。但是沒有說到如何配置mybatis的事務管理,在編寫業務的過程中,會需要進行事務處理,當需要執行多條插入語句時,如果前幾條成功,而最后一條失敗,那么我們需要回滾數據庫操作,保持數據的一致性和完整性,此時,就需要利用DB的事務處理。事務是恢復和並發控制的基本單位。
簡單來說,所謂的事務,是一個操作序列,這些操作要么都執行,要么都不執行,它是一個不可分割的工作單位。
事務應該具有4個屬性:原子性、一致性、隔離性、持久性。這四個屬性通常稱為ACID特性。
原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要么都做,要么都不做。
一致性(consistency)。事務必須是使數據庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。
隔離性(isolation)。一個事務的執行不能被其他事務干擾。即一個事務內部的操作及使用的數據對並發的其他事務是隔離的,並發執行的各個事務之間不能互相干擾。
持久性(durability)。持續性也稱永久性(permanence),指一個事務一旦提交,它對數據庫中數據的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
MyBatis集成Spring事務管理
在SSM框架中,使用的是Spring的事務管理機制。Spring可以使用編程式實現事務,聲明式實現事務以及注解式實現事務。本文主要說一下如何使用注解式@Transanctional實現實現事務管理。
本文代碼例子基於上一篇博文,具體代碼《SSM三大框架整合詳細教程》中已經給出。簡單看下目錄結構以及實體類:
1、配置spring-mybatis.xml文件
如要實現注解形式的事務管理,只需要在配置文件中加入以下代碼即可:
- <!-- 開啟事務注解驅動 -->
- <tx:annotation-driven />
- <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
當然,如果此時xml文件報錯,那是由於沒有引入xmlns和schema導致的,無法識別文檔結構。引入頭文件即可,以下是我的,根據自己需要引入:
- <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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.1.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
在此用一個小例子來測試事務管理是否成功配置。代碼基礎是SSM框架搭建里面的測試代碼。我們現在注意@Transactional只能被應用到public方法上,對於其它非public的方法,如果標記了@Transactional也不會報錯,但方法沒有事務功能。
- /**
- * 事務處理必須拋出異常,Spring才會幫助事務回滾
- * @param users
- */
- @Transactional
- @Override
- public void insertUser(List<User> users) {
- // TODO Auto-generated method stub
- for (int i = 0; i < users.size(); i++) {
- if(i<2){
- this.userDao.insert(users.get(i));
- }
- else {
- throw new RuntimeException();
- }
- }
- }
接下來在測試類中添加如下方法進行測試:
- @Test
- public void testTransaction(){
- List<User> users = new ArrayList<User>();
- for(int i=1;i<5;i++){
- User user = new User();
- user.setAge(i);
- user.setPassword(i+"111111");
- user.setUserName("測試"+i);
- users.add(user);
- }
- this.userService.insertUser(users);
- }