亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring集成事務代碼實例

 更新時間:2023年10月18日 09:09:03   作者:喜上編程  
這篇文章主要介紹了Spring集成事務代碼實例,pring事務的本質(zhì)其實就是數(shù)據(jù)庫對事務的支持,使用JDBC的事務管理機制,就是利用java.sql.Connection對象完成對事務的提交,需要的朋友可以參考下

Spring事務

Spring事務的本質(zhì)其實就是數(shù)據(jù)庫對事務的支持,使用JDBC的事務管理機制,就是利用java.sql.Connection對象完成對事務的提交。

有了Spring,我們再也無需要去處理獲得連接、關閉連接、事務提交和回滾等這些操作,使得我們把更多的精力放在處理業(yè)務上。

事實上Spring并不直接管理事務,而是提供了多種事務管理器。他們將事務管理的職責委托給Hibernate或者JTA等持久化機制所提供的相關平臺框架的事務來實現(xiàn)。

一、編程式事務

編程式事務管理我們可以通過PlatformTransactionManager實現(xiàn)來進行事務管理,同樣的Spring也為我們提供了模板類TransactionTemplate進行事務管理,下面主要介紹模板類,我們需要在配置文件中配置。

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ù)據(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>
<!--    配置平臺事物管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--配置平臺事物管理模板    事務管理的模板類-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="dataSourceTransactionManager"></property>
    </bean>
</beans>

編寫DAO接口

package com.it.spring.tx.dao;
/**
 * 實現(xiàn)轉賬業(yè)務
 */
public interface
AccountDAO {

    //出賬
    void outMoney(String from,Double money);
    //入賬
    void inMoney(String in,Double money);   
}

DAO實現(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類有關JdbcTemplate的注入的相關工作量。
public class AccountDAOImpl extends JdbcDaoSupport implements AccountDAO {
    @Resource
    private DataSource dataSource;
    //初始化dataSources
    @PostConstruct
    private  void init(){
        //調(diào)用JdbcDaoSupport的setDataSource方法  或者使用帶參構造函數(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;
/**
 * 實現(xiàn)轉賬業(yè)務
 */
public interface AccountService {
    void transfer(String from,String to,Double money);
}

service實現(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的編程式事務管理是使用模板方法設計模式對原始事務管理方式的封裝
    @Resource
   private TransactionTemplate transactionTemplate;
//    @Override
//    public void transfer(String from, String to, Double money) {
//        accountDAO.outMoney(from,money);
        System.out.println(12/0);
//        //添加事務進行解決   使用TransactionTemplate模塊
//        accountDAO.inMoney(to,money);
//    }


@Override
public void transfer(String from, String to, Double money) {
    //所以當我們借助TransactionTemplate.execute( ... )執(zhí)行事務管理的時候,傳入的參數(shù)有兩種選擇:
    //1、TransactionCallback
    //2、TransactionCallbackWithoutResult
    //兩種區(qū)別從命名看就相當明顯了,一個是有返回值,一個是無返回值。這個的選擇就取決于你是讀

//    //設置事務傳播屬性
//    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//    // 設置事務的隔離級別,設置為讀已提交(默認是ISOLATION_DEFAULT:使用的是底層數(shù)據(jù)庫的默認的隔離級別)
//    transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
//    // 設置是否只讀,默認是false
//    transactionTemplate.setReadOnly(true);
//    // 默認使用的是數(shù)據(jù)庫底層的默認的事務的超時時間
//    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);
     }
}

二、聲明式事務

聲明式事務管理有兩種常用的方式,一種是基于tx和aop命名空間的xml配置文件,一種是基于@Transactional注解,隨著Spring和Java的版本越來越高,大家越趨向于使用注解的方式,下面我們兩個都說。

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>
    <!--配置平臺事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    配置增強(就是自定義的的切面) -->

<!--     配置事物增強-->

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--         propagation事務傳播行為    isolation隔離機制-->
        <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>
<!--        設置切點-->
        <aop:pointcut id="pointcut1" expression="execution(* com.com.it.spring.tx2.service.AccountServiceImpl.transfer(..))"></aop:pointcut>
<!--        aop:aspect 多個通知和多個切入點的組合-->
        <!--aop:advisor 單個通知和單個切入點的組合-->
        <aop:advisor pointcut-ref="pointcut1" advice-ref="txAdvice"></aop:advisor>
    </aop:config>
</beans>

service實現(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注解

這種方式最簡單,也是最為常用的,只需要在配置文件中開啟對注解事務管理的支持。

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>
    <!--配置平臺事物管理器 -->
    <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實現(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è)務層添加注解
 @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管理事務的方式。感謝閱讀。

到此這篇關于Spring集成事務代碼實例的文章就介紹到這了,更多相關Spring事務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java編譯器用maven打war包出錯解決辦法

    Java編譯器用maven打war包出錯解決辦法

    這篇文章主要介紹了用maven打war包出錯的解決辦法,需要的朋友可以參考下
    2018-03-03
  • 詳細解讀JAVA多線程實現(xiàn)的三種方式

    詳細解讀JAVA多線程實現(xiàn)的三種方式

    本篇文章主要介紹了詳細解讀JAVA多線程實現(xiàn)的三種方式,主要包括繼承Thread類、實現(xiàn)Runnable接口、使用ExecutorService、Callable、Future實現(xiàn)有返回結果的多線程。有需要的可以了解一下。
    2016-11-11
  • Java 非阻塞I/O使用方法

    Java 非阻塞I/O使用方法

    這篇文章主要介紹了Java 非阻塞I/O使用方法,文中涉及非阻塞I/O的簡介,同時向大家展示了利用非阻塞I/O實現(xiàn)客戶端的方法,需要的朋友可以參考下。
    2017-09-09
  • java使用FFmpeg提取音頻的實現(xiàn)示例

    java使用FFmpeg提取音頻的實現(xiàn)示例

    在Java開發(fā)中,我們經(jīng)常會遇到需要使用FFmpeg來處理音視頻文件的情況,本文主要介紹了java使用FFmpeg提取音頻的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • java數(shù)據(jù)結構-堆實現(xiàn)優(yōu)先隊列

    java數(shù)據(jù)結構-堆實現(xiàn)優(yōu)先隊列

    通常都把隊列比喻成排隊買東西,大家都很守秩序,先排隊的人就先買東西。但是優(yōu)先隊列有所不同,它不遵循先進先出的規(guī)則,而是根據(jù)隊列中元素的優(yōu)先權,優(yōu)先權最大的先被取出,這篇文章主要介紹了java數(shù)據(jù)結構-堆實現(xiàn)優(yōu)先隊列,感興趣的朋友一起看看吧
    2021-08-08
  • java ArrayList按照同一屬性進行分組

    java ArrayList按照同一屬性進行分組

    這篇文章主要介紹了java ArrayList按照同一屬性進行分組的相關資料,需要的朋友可以參考下
    2017-02-02
  • Java數(shù)組的定義、初始化、及二維數(shù)組用法分析

    Java數(shù)組的定義、初始化、及二維數(shù)組用法分析

    這篇文章主要介紹了Java數(shù)組的定義、初始化、及二維數(shù)組用法,結合具體實例形式分析了java數(shù)組概念、功能、數(shù)組定義、靜態(tài)數(shù)組、動態(tài)數(shù)組、二維數(shù)組等相關使用技巧,需要的朋友可以參考下
    2019-01-01
  • java 獲取對象中為null的字段實例代碼

    java 獲取對象中為null的字段實例代碼

    這篇文章主要介紹了java 獲取對象中為null的字段實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-04-04
  • 你知道怎么從Python角度學習Java基礎

    你知道怎么從Python角度學習Java基礎

    這篇文章主要為大家詳細介紹了Python角度學習Java基礎的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • 推薦幾款非常實用的IDEA插件小結

    推薦幾款非常實用的IDEA插件小結

    這篇文章主要介紹了推薦幾款非常實用的IDEA插件小結,解決你開發(fā)中可望而又不好找的插件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01

最新評論