使用spring框架實現數據庫事務處理方式

使用spring框架實現數據庫事務處理

事務對於數據庫來說是,是對sql語句的一系列操作,這些操作被組織成為一個事務。事務具有原子性的,要麼全部執行,要麼不執行。若事務中sql語句發生錯誤,事務需要對已經執行的sql進行回滾操作,撤銷先前對數據庫的操作,防止數據庫出現錯誤狀態。

JDBC對數據庫事務處理的支持

jdbc本身提供瞭對數據庫處理的支持,使用java.sql.Connection對象完成事務的提交。使用Connection提交數據庫事務處理如下:

在這裡插入圖片描述

發現裡面有一個方法叫setAutoCommit(),設置為true時,就是自動提交sql,如果設置為false時,sql語句的提交由程序負責,應用程序必須調用Commit方法,同時在執行sql語句異常處理塊中調用rollback方法,對異常發生前進行的數據庫進行回滾。

在企業級中,事務一般都是並發執行的,當事務並發執行時,就會發生數據庫同步的問題,具體問題可分為下面四種類型:

  • 臟讀:
  • 不可重復讀:
  • 丟失更新:
  • 幻讀:

為瞭解決上面的四種問題,解決事務並發的問題

JDBC定義瞭五種事務隔離級別來解決這些並發導致的問題

  • transaction_read_uncommitted:數據級別最低,俗稱臟讀,在沒有提交數據時,就已經讀取到已經更新的數據。
  • transaction_read_committed:當一個事務進行查詢時,允許讀取提交前的數據,數據提交後,當前查詢就可以讀取到數據,update數據的時候並不鎖住表。(最長使用)
  • transaction_repeatable_read:當一個事務進行查詢時,不允許讀取其他事務更新的數據,可以讀取其他事務新增的數據。
  • transaction_serializable:當一個事務進行查詢時,不允許任何對這個事務進行查詢,就是把並行改成瞭串行。不提倡使用。

在spring框架中調用一個數據庫事務處理分三步走:

  • 第一步就是配置數據源就是配置數據庫的名稱和密碼,地址等。
  • 第二步就是聲明事務管理TransactionManagerspring框架提供瞭PlatformTransactionManager作為事務管理類的頂層接口,聲明瞭初始化事務,提交事務,回滾事務等接口。接口實現由具體的數據庫驅動類實現。具體包括DataTransactionManager等實現類。但是主要還是使用的是DataTransactionManager類。
  • 在這裡插入圖片描述
  • 定義可以執行事務的DAO類DAO提供瞭應用程序訪問數據源必要的接口和方法。

spring 事務實現方式有哪些

編程式事務管理,

在代碼中調用 commit()、rollback()等事務管理相關的方法

maven pom.xml文件

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-beans</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
 
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
 
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aop</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
 
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-tx</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
 
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
 
<!-- mysql驅動 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.18</version>
</dependency>

編程式事務管理,可以通過 java.sql.Connection 控制事務。spring 配置文件

<?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"
	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">
        
	<bean id="driver" class="com.mysql.jdbc.Driver"></bean>
 
	<bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<constructor-arg index="0" name="driver" ref="driver" />
		<constructor-arg index="1">
			<value>jdbc:mysql://localhost:3306/test</value>
		</constructor-arg>
		<constructor-arg index="2">
			<value>root</value>
		</constructor-arg>
		<constructor-arg index="3">
			<value>root</value>
		</constructor-arg>
	</bean>	
</beans>

測試代碼

package constxiong.interview.transaction; 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; 
import javax.sql.DataSource; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class TransactionTest {
 
	public static void main(String[] args) throws Exception {
		testManualTransaction();//測試函數式控制事務
	}
	
	private static void testManualTransaction() throws SQLException {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
		DataSource ds = (DataSource)context.getBean("datasource");
		Connection conn = ds.getConnection();
		try {
			initTable(conn);//初始化表
			conn.setAutoCommit(false);//設置不自動提交事務
			queryUsers(conn);//查詢打印用戶表
			deleteUser(conn);//刪除 id=1 用戶
			conn.rollback();//回滾
			queryUsers(conn);//查詢打印用戶表
		} finally {
			conn.close();
		}
	}
 
	private static void initTable(Connection conn) throws SQLException {
		conn.createStatement().execute("drop table if exists user");
		conn.createStatement().execute("create table user(id int, username varchar(60)) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");//是否支持事務與數據庫引擎有關,此處刪除 ENGINE=InnoDB DEFAULT CHARSET=utf8 可能不支持事務
		conn.createStatement().execute("insert into user values(1, 'user1')");
		conn.createStatement().execute("insert into user values(2, 'user2')");
	}
 
	private static void deleteUser(Connection conn) throws SQLException {
		conn.createStatement().execute("delete from user where id = 1");
	}
 
	private static void queryUsers(Connection conn) throws SQLException {
		Statement st = conn.createStatement();
		st.execute("select * from user");
		ResultSet rs = st.getResultSet();
		while (rs.next()) {
			System.out.print(rs.getString("id"));
			System.out.print(" ");
			System.out.print(rs.getString("username"));
			System.out.println();
		}
	}	
}

刪除用戶語句回滾,打印出兩個用戶

1 user1

2 user2

1 user1

2 user2

TransactionProxyFactoryBean 的聲明式事務管理

新增 UserDao 接口

package constxiong.interview.transaction; 
import java.util.List;
import java.util.Map; 
public interface UserDao { 
	/**
	 * 查詢用戶
	 * @return
	 */
	public List<Map<String, Object>> getUsers();
	
	/**
	 * 刪除用戶
	 * @param id
	 * @return
	 */
	public int deleteUser(int id);	
}

新增 UserDao 實現

package constxiong.interview.transaction; 
import java.util.List;
import java.util.Map; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
	
	/**
	 * 查詢用戶
	 * @return
	 */
	public List<Map<String, Object>> getUsers() {
		String sql = "select * from user";
		return this.getJdbcTemplate().queryForList(sql);
	}
	
	/**
	 * 刪除用戶
	 * @param id
	 * @return
	 */
	public int deleteUser(int id){
		String sql = "delete from user where id = " + id;
		int result = this.getJdbcTemplate().update(sql);
		if (id == 1) {
			throw new RuntimeException();
		}
		return result;
	}
}

修改 spring 配置文件,添加事務管理器 DataSourceTransactionManager 和事務代理類 TransactionProxyFactoryBean

<?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"
	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">
        
	<bean id="driver" class="com.mysql.jdbc.Driver"></bean>
	
	<bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<constructor-arg index="0" name="driver" ref="driver" />
		<constructor-arg index="1">
			<value>jdbc:mysql://localhost:3306/test</value>
		</constructor-arg>
		<constructor-arg index="2">
			<value>root</value>
		</constructor-arg>
		<constructor-arg index="3">
			<value>root</value>
		</constructor-arg>
	</bean>
	
	<bean id="userDao" class="constxiong.interview.transaction.UserDaoImpl">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<!-- 事務管理器 -->
	<bean id="tracnsactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<bean id="userProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="tracnsactionManager"></property>
		<property name="target" ref="userDao"></property>
		<property name="transactionAttributes">
			<props>
				<!-- 主要 key 是方法   
					ISOLATION_DEFAULT  事務的隔離級別
					PROPAGATION_REQUIRED  傳播行為
				-->
				<!-- -Exception 表示發生指定異常回滾,+Exception 表示發生指定異常提交 -->
				<prop key="deleteUser">-java.lang.RuntimeException</prop>
			</props>
		</property>
	</bean>
	
</beans>

測試代碼

package constxiong.interview.transaction; 
import java.util.Map; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class TransactionTest { 
	static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");	
	public static void main(String[] args) throws Exception {
		testUseTransactionProxy(); //測試使用 spring TransactionProxyFactoryBean
	}
	
	private static void testUseTransactionProxy() {
		final UserDao userDao = (UserDao)context.getBean("userProxy");
		printUsers(userDao);//打印用戶
		userDao.deleteUser(1);//刪除 id=1 用戶
	}
 
	private static void printUsers(UserDao userDao) {
		for (Map<String, Object> user : userDao.getUsers()) {
			System.out.println(user);
		}
	} 
}

結果輸出

{id=1, username=user1}
{id=2, username=user2}
Exception in thread “main” java.lang.RuntimeException
at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy3.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testUseTransactionProxy(TransactionTest.java:32)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)

註解 @Transactional 的聲明式事務管理

UserDaoImpl 刪除用戶方法添加註解 @Transactional(rollbackFor=RuntimeException.class) 出現 RuntimeException 回滾

package constxiong.interview.transaction; 
import java.util.List;
import java.util.Map; 
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.transaction.annotation.Transactional; 
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {	
	/**
	 * 查詢用戶
	 * @return
	 */
	public List<Map<String, Object>> getUsers() {
		String sql = "select * from user";
		return this.getJdbcTemplate().queryForList(sql);
	}
	
	/**
	 * 刪除用戶
	 * @param id
	 * @return
	 */
	@Transactional(rollbackFor=RuntimeException.class)
	public int deleteUser(int id){
		String sql = "delete from user where id = " + id;
		int result = this.getJdbcTemplate().update(sql);
		if (id == 1) {
			throw new RuntimeException();
		}
		return result;
	}
}

修改 spring 配置文件,開啟 spring 的事務註解能力

<?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/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
	    http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
	<bean id="driver" class="com.mysql.jdbc.Driver"></bean>
	
	<bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<constructor-arg index="0" name="driver" ref="driver" />
		<constructor-arg index="1">
			<value>jdbc:mysql://localhost:3306/test</value>
		</constructor-arg>
		<constructor-arg index="2">
			<value>root</value>
		</constructor-arg>
		<constructor-arg index="3">
			<value>root</value>
		</constructor-arg>
	</bean>
	
	<bean id="userDao" class="constxiong.interview.transaction.UserDaoImpl">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<!-- 事務管理器 -->
	<bean id="tracnsactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<!-- 啟用事務註解 -->
	<tx:annotation-driven transaction-manager="tracnsactionManager"/>	
</beans>

測試代碼

package constxiong.interview.transaction; 
import java.util.Map; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class TransactionTest { 
	static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");	
	public static void main(String[] args) throws Exception {
		testAnnotationTransaction();
	}	
	
	private static void testAnnotationTransaction() {
		UserDao userDao = (UserDao)context.getBean("userDao");
		printUsers(userDao);
		userDao.deleteUser(1);
	} 
 
	private static void printUsers(UserDao userDao) {
		for (Map<String, Object> user : userDao.getUsers()) {
			System.out.println(user);
		}
	} 
}

輸出結果

{id=1, username=user1}
{id=2, username=user2}
Exception in thread “main” java.lang.RuntimeException
at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy5.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testAnnotationTransaction(TransactionTest.java:20)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)

Aspectj AOP 配置(註解)事務

maven pom.xml 添加 Aspectj 的支持

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.13</version>
</dependency>

去除 UserDaoImpl 註解@Transactional(rollbackFor=RuntimeException.class)

package constxiong.interview.transaction; 
import java.util.List;
import java.util.Map; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {	
	/**
	 * 查詢用戶
	 * @return
	 */
	public List<Map<String, Object>> getUsers() {
		String sql = "select * from user";
		return this.getJdbcTemplate().queryForList(sql);
	}
	
	/**
	 * 刪除用戶
	 * @param id
	 * @return
	 */
	public int deleteUser(int id){
		String sql = "delete from user where id = " + id;
		int result = this.getJdbcTemplate().update(sql);
		if (id == 1) {
			throw new RuntimeException();
		}
		return result;
	}
}

修改 spring 配置文件,織入切面

<?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"
	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/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.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">
        
	<bean id="driver" class="com.mysql.jdbc.Driver"></bean>
	
	<bean id="datasource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<constructor-arg index="0" name="driver" ref="driver" />
		<constructor-arg index="1">
			<value>jdbc:mysql://localhost:3306/test</value>
		</constructor-arg>
		<constructor-arg index="2">
			<value>root</value>
		</constructor-arg>
		<constructor-arg index="3">
			<value>root</value>
		</constructor-arg>
	</bean>
	
	<bean id="userDao" class="constxiong.interview.transaction.UserDaoImpl">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<!-- 事務管理器 -->
	<bean id="tracnsactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="datasource"></property>
	</bean>
	
	<tx:advice id="txAdvice" transaction-manager="tracnsactionManager">
		<tx:attributes>
			<!-- 為連接點指定事務屬性 -->
			<tx:method name="deleteUser" rollback-for="java.lang.RuntimeException"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<!-- 切入點配置 -->
		<aop:pointcut id="point" expression="execution(* *constxiong.interview.transaction.UserDao.deleteUser(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
	</aop:config>	
</beans>

測試代碼

package constxiong.interview.transaction; 
import java.util.Map; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class TransactionTest { 
	static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");	
	public static void main(String[] args) throws Exception {
		testAspectjTransaction();
	}	
	
	private static void testAspectjTransaction() {
		UserDao userDao = (UserDao)context.getBean("userDao");
		printUsers(userDao);
		userDao.deleteUser(1);
	} 
 
	private static void printUsers(UserDao userDao) {
		for (Map<String, Object> user : userDao.getUsers()) {
			System.out.println(user);
		}
	} 
}

輸出結果

{id=1, username=user1}
{id=2, username=user2}
Exception in thread “main” java.lang.RuntimeException
at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy2.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testAnnotationTransaction(TransactionTest.java:20)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)

PS:

這篇僅用事務回滾為例,瞭解 spring 事務控制,還需要關註數據庫的ACID四種特性、事務傳播特性、事務的隔離級別(臟讀、不可重復讀、幻讀)。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: