Spring集成事務(wù)代碼實(shí)例
Spring事務(wù)
Spring事務(wù)的本質(zhì)其實(shí)就是數(shù)據(jù)庫(kù)對(duì)事務(wù)的支持,使用JDBC的事務(wù)管理機(jī)制,就是利用java.sql.Connection對(duì)象完成對(duì)事務(wù)的提交。
有了Spring,我們?cè)僖矡o(wú)需要去處理獲得連接、關(guān)閉連接、事務(wù)提交和回滾等這些操作,使得我們把更多的精力放在處理業(yè)務(wù)上。
事實(shí)上Spring并不直接管理事務(wù),而是提供了多種事務(wù)管理器。他們將事務(wù)管理的職責(zé)委托給Hibernate或者JTA等持久化機(jī)制所提供的相關(guān)平臺(tái)框架的事務(wù)來(lái)實(shí)現(xiàn)。
一、編程式事務(wù)
編程式事務(wù)管理我們可以通過(guò)PlatformTransactionManager實(shí)現(xiàn)來(lái)進(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 "> <!-- 開(kāi)啟注解--> <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ù)庫(kù)的值 spring管理c3p0數(shù)據(jù)庫(kù)連接池--> <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>
編寫(xiě)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就是為了簡(jiǎn)化我們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è)是無(wú)返回值。這個(gè)的選擇就取決于你是讀 // //設(shè)置事務(wù)傳播屬性 // transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); // // 設(shè)置事務(wù)的隔離級(jí)別,設(shè)置為讀已提交(默認(rèn)是ISOLATION_DEFAULT:使用的是底層數(shù)據(jù)庫(kù)的默認(rèn)的隔離級(jí)別) // transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); // // 設(shè)置是否只讀,默認(rèn)是false // transactionTemplate.setReadOnly(true); // // 默認(rèn)使用的是數(shù)據(jù)庫(kù)底層的默認(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(); } } }); } }
測(cè)試類
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的版本越來(lái)越高,大家越趨向于使用注解的方式,下面我們兩個(gè)都說(shuō)。
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ù)庫(kù)連接池--> <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); } }
測(cè)試類
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注解
這種方式最簡(jiǎn)單,也是最為常用的,只需要在配置文件中開(kāi)啟對(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ù)庫(kù)連接池--> <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> <!-- 開(kāi)啟事物注解--> <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)文章
詳細(xì)解讀JAVA多線程實(shí)現(xiàn)的三種方式
本篇文章主要介紹了詳細(xì)解讀JAVA多線程實(shí)現(xiàn)的三種方式,主要包括繼承Thread類、實(shí)現(xiàn)Runnable接口、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程。有需要的可以了解一下。2016-11-11java使用FFmpeg提取音頻的實(shí)現(xiàn)示例
在Java開(kāi)發(fā)中,我們經(jīng)常會(huì)遇到需要使用FFmpeg來(lái)處理音視頻文件的情況,本文主要介紹了java使用FFmpeg提取音頻的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01java數(shù)據(jù)結(jié)構(gòu)-堆實(shí)現(xiàn)優(yōu)先隊(duì)列
通常都把隊(duì)列比喻成排隊(duì)買東西,大家都很守秩序,先排隊(duì)的人就先買東西。但是優(yōu)先隊(duì)列有所不同,它不遵循先進(jìn)先出的規(guī)則,而是根據(jù)隊(duì)列中元素的優(yōu)先權(quán),優(yōu)先權(quán)最大的先被取出,這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)-堆實(shí)現(xiàn)優(yōu)先隊(duì)列,感興趣的朋友一起看看吧2021-08-08Java數(shù)組的定義、初始化、及二維數(shù)組用法分析
這篇文章主要介紹了Java數(shù)組的定義、初始化、及二維數(shù)組用法,結(jié)合具體實(shí)例形式分析了java數(shù)組概念、功能、數(shù)組定義、靜態(tài)數(shù)組、動(dòng)態(tài)數(shù)組、二維數(shù)組等相關(guān)使用技巧,需要的朋友可以參考下2019-01-01java 獲取對(duì)象中為null的字段實(shí)例代碼
這篇文章主要介紹了java 獲取對(duì)象中為null的字段實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04你知道怎么從Python角度學(xué)習(xí)Java基礎(chǔ)
這篇文章主要為大家詳細(xì)介紹了Python角度學(xué)習(xí)Java基礎(chǔ)的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-02-02