Spring 事務管理

ACID是數據庫事務正確執行的四個基本要素。包含:原子性(Atomicity)、一致性(Consistency)、隔離性(Isolation)、持久性(Durability)。

Spring對提供了數據庫事務管理機制,通過配置文件和註解的方式,可以很方便的進行事務管理。

1、配置文件

<?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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


<!-- 指定數據源的配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>

<!--
利用 BasicDataSource配置數據源
org.apache.commons.dbcp2.BasicDataSource 需要commons-dbcp2-2.1.1.jar,依賴commons-pool2-2.4.2.jar
-->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>

<!-- 配置spring的jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 
配置spring的 namedParameterJdbcTemplate,支持sql語句的具名參數
namedParameterJdbcTemplate的dataSource是以構造函數參數方式配置,而不是屬性
-->
<bean id="namedParameterJdbcTemplate" 
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>

<!-- spring JDBC事務管理的bean -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 開啓根據註解@Transactional自動加載事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>


2、TestTX.java

import static org.junit.Assert.*;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;


public class TestTX {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

/**

* @Transactional 註解增加在方法上方
* 轉賬過程,先扣除一方賬號餘額,再增加另一方賬號餘額,任何一方出錯,都要回滾事務
*/
@Transactional// 增加在方法上方,整個方法受Spring 事務管理
@Test
public void testTransfer(String user1, String user2, int value) {
// 1. user1的餘額減去value
DecreaseBalance(user1, value);

// 2. user2的餘額增加value
IncreaseBalance(user2, value);
}


}

發佈了46 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章