Spring集成事務(wù)代碼實(shí)例
Spring事務(wù)
Spring事務(wù)的本質(zhì)其實(shí)就是數(shù)據(jù)庫對(duì)事務(wù)的支持,使用JDBC的事務(wù)管理機(jī)制,就是利用java.sql.Connection對(duì)象完成對(duì)事務(wù)的提交。
有了Spring,我們?cè)僖矡o需要去處理獲得連接、關(guān)閉連接、事務(wù)提交和回滾等這些操作,使得我們把更多的精力放在處理業(yè)務(wù)上。
事實(shí)上Spring并不直接管理事務(wù),而是提供了多種事務(wù)管理器。他們將事務(wù)管理的職責(zé)委托給Hibernate或者JTA等持久化機(jī)制所提供的相關(guān)平臺(tái)框架的事務(wù)來實(shí)現(xiàn)。
一、編程式事務(wù)
編程式事務(wù)管理我們可以通過PlatformTransactionManager實(shí)現(xiàn)來進(jìn)行事務(wù)管理,同樣的Spring也為我們提供了模板類TransactionTemplate進(jìn)行事務(wù)管理,下面主要介紹模板類,我們需要在配置文件中配置。
applicationContext.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 開啟注解-->
<context:component-scan base-package="com.it.spring.tx"></context:component-scan>
<!-- 引入工程中src下的db.properties文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 設(shè)置連接數(shù)據(jù)庫的值 spring管理c3p0數(shù)據(jù)庫連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 配置平臺(tái)事物管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置平臺(tái)事物管理模板 事務(wù)管理的模板類-->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="dataSourceTransactionManager"></property>
</bean>
</beans>
編寫DAO接口
package com.it.spring.tx.dao;
/**
* 實(shí)現(xiàn)轉(zhuǎn)賬業(yè)務(wù)
*/
public interface
AccountDAO {
//出賬
void outMoney(String from,Double money);
//入賬
void inMoney(String in,Double money);
}
DAO實(shí)現(xiàn)類
package com.it.spring.tx.dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Repository
//JdbcDaoSupport就是為了簡化我們dao類有關(guān)JdbcTemplate的注入的相關(guān)工作量。
public class AccountDAOImpl extends JdbcDaoSupport implements AccountDAO {
@Resource
private DataSource dataSource;
//初始化dataSources
@PostConstruct
private void init(){
//調(diào)用JdbcDaoSupport的setDataSource方法 或者使用帶參構(gòu)造函數(shù)
setDataSource(dataSource);
}
@Override
public void outMoney(String from, Double money) {
System.out.println(getJdbcTemplate());
getJdbcTemplate().update("update account set money=money-? where id=?",money,from);
}
@Override
public void inMoney(String in, Double money) {
getJdbcTemplate().update("update account set money=money+? where id=?",money,in);
}
}
service接口
package com.it.spring.tx.service;
/**
* 實(shí)現(xiàn)轉(zhuǎn)賬業(yè)務(wù)
*/
public interface AccountService {
void transfer(String from,String to,Double money);
}
service實(shí)現(xiàn)類
package com.it.spring.tx.service;
import com.it.spring.tx.dao.AccountDAO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
@Service
public class AccountServiceImpl implements AccountService {
@Resource
AccountDAO accountDAO;
//而TransactionTemplate的編程式事務(wù)管理是使用模板方法設(shè)計(jì)模式對(duì)原始事務(wù)管理方式的封裝
@Resource
private TransactionTemplate transactionTemplate;
// @Override
// public void transfer(String from, String to, Double money) {
// accountDAO.outMoney(from,money);
System.out.println(12/0);
// //添加事務(wù)進(jìn)行解決 使用TransactionTemplate模塊
// accountDAO.inMoney(to,money);
// }
@Override
public void transfer(String from, String to, Double money) {
//所以當(dāng)我們借助TransactionTemplate.execute( ... )執(zhí)行事務(wù)管理的時(shí)候,傳入的參數(shù)有兩種選擇:
//1、TransactionCallback
//2、TransactionCallbackWithoutResult
//兩種區(qū)別從命名看就相當(dāng)明顯了,一個(gè)是有返回值,一個(gè)是無返回值。這個(gè)的選擇就取決于你是讀
// //設(shè)置事務(wù)傳播屬性
// transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
// // 設(shè)置事務(wù)的隔離級(jí)別,設(shè)置為讀已提交(默認(rèn)是ISOLATION_DEFAULT:使用的是底層數(shù)據(jù)庫的默認(rèn)的隔離級(jí)別)
// transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
// // 設(shè)置是否只讀,默認(rèn)是false
// transactionTemplate.setReadOnly(true);
// // 默認(rèn)使用的是數(shù)據(jù)庫底層的默認(rèn)的事務(wù)的超時(shí)時(shí)間
// transactionTemplate.setTimeout(30000);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
try {
accountDAO.outMoney(from, money);
System.out.println(12 / 0);
accountDAO.inMoney(to, money);
} catch (Exception e){
//回滾狀態(tài)
transactionStatus.setRollbackOnly();
}
}
});
}
}
測試類
package com.it.spring.tx.test;
import com.it.spring.tx.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTxTest1 {
@Resource
AccountService accountService;
@Test
public void Test1(){
accountService.transfer("18","17",1000.0);
}
}
二、聲明式事務(wù)
聲明式事務(wù)管理有兩種常用的方式,一種是基于tx和aop命名空間的xml配置文件,一種是基于@Transactional注解,隨著Spring和Java的版本越來越高,大家越趨向于使用注解的方式,下面我們兩個(gè)都說。
1.基于tx和aop命名空間的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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.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">
<context:component-scan base-package="com.it.spring.tx2.*"></context:component-scan>
<!-- 引入工程中src下的db.properties文件2-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- spring管理c3p0數(shù)據(jù)庫連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="password" value="${password}"></property>
<property name="user" value="${user}"></property>
</bean>
<!--配置平臺(tái)事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置增強(qiáng)(就是自定義的的切面) -->
<!-- 配置事物增強(qiáng)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- propagation事務(wù)傳播行為 isolation隔離機(jī)制-->
<tx:attributes>
<!-- <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"></tx:method>-->
<!-- <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"></tx:method>-->
<!-- <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"></tx:method>-->
<!-- <tx:method name="query*" read-only="true"></tx:method>-->
<tx:method name="*" propagation="REQUIRED"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置AOP-->
<aop:config>
<!-- 設(shè)置切點(diǎn)-->
<aop:pointcut id="pointcut1" expression="execution(* com.com.it.spring.tx2.service.AccountServiceImpl.transfer(..))"></aop:pointcut>
<!-- aop:aspect 多個(gè)通知和多個(gè)切入點(diǎn)的組合-->
<!--aop:advisor 單個(gè)通知和單個(gè)切入點(diǎn)的組合-->
<aop:advisor pointcut-ref="pointcut1" advice-ref="txAdvice"></aop:advisor>
</aop:config>
</beans>
service實(shí)現(xiàn)類發(fā)生變化
package com.it.spring.tx2.service;
import com.it.spring.tx2.dao.AccountDAO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource
AccountDAO accountDAO;
@Override
public void transfer(String from, String to, Double money) {
accountDAO.outMoney(from,money);
// System.out.println(12/0);
accountDAO.inMoney(to,money);
}
}
測試類
package com.it.spring.tx2.test;
import com.it.spring.tx2.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringTxTest2 {
@Resource
AccountService accountService;
@Test
public void fun1(){
accountService.transfer("11","10",1000.0);
}
}
2.基于@Transactional注解
這種方式最簡單,也是最為常用的,只需要在配置文件中開啟對(duì)注解事務(wù)管理的支持。
applicationContext3.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.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">
<context:component-scan base-package="com.it.spring.tx3.*"></context:component-scan>
<!-- 引入工程中src下的db.properties文件2-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- spring管理c3p0數(shù)據(jù)庫連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="password" value="${password}"></property>
<property name="user" value="${user}"></property>
</bean>
<!--配置平臺(tái)事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 開啟事物注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
services實(shí)現(xiàn)類
package com.it.spring.tx3.service;
import com.it.spring.tx3.dao.AccountDAO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
//在業(yè)務(wù)層添加注解
@Service
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {
@Resource
AccountDAO accountDAO;
@Override
public void transfer(String from, String to, Double money) {
accountDAO.outMoney(from,money);
// System.out.println(12/0);
accountDAO.inMoney(to,money);
}
}
以上就是Spring管理事務(wù)的方式。感謝閱讀。
到此這篇關(guān)于Spring集成事務(wù)代碼實(shí)例的文章就介紹到這了,更多相關(guān)Spring事務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Builder模式的實(shí)現(xiàn)詳解
在設(shè)計(jì)模式中對(duì)Builder模式的定義是用于構(gòu)建復(fù)雜對(duì)象的一種模式,所構(gòu)建的對(duì)象往往需要多步初始化或賦值才能完成。下面這篇文章主要給大家介紹了在Java各個(gè)版本中Builder模式實(shí)現(xiàn)的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考學(xué)習(xí)。2017-05-05
MyBatis實(shí)現(xiàn)注冊(cè)及獲取Mapper
本文主要介紹了MyBatis實(shí)現(xiàn)注冊(cè)及獲取Mapper,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03
java中orElse和orElseGet方法區(qū)別小結(jié)
這篇文章主要給大家介紹了關(guān)于java中orElse和orElseGet方法區(qū)別的相關(guān)資料,兩者之間的區(qū)別細(xì)微,但是卻在某些場景下顯的很重要,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10
使用hibernate和struts2實(shí)現(xiàn)分頁功能的示例
本篇文章主要介紹了使用hibernate和struts2實(shí)現(xiàn)分頁功能,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01

