spring jdbcTemplate 事務,各種詭異,包你醍醐灌頂!

来源:http://www.cnblogs.com/youzhibing/archive/2016/12/02/6127250.html
-Advertisement-
Play Games

前言 項目框架主要是spring,持久層框架沒有用mybtis,用的是spring 的jdbc; 業務需求:給應用添加領域(一個領域包含多個應用,一個應用可能屬於多個領域,一般而言一個應用只屬於一個領域),要求是給應用添加領域的時候,先將該應用已有的領域都刪除,之後再將選中的領域添加到資料庫; 為了 ...


前言

  項目框架主要是spring,持久層框架沒有用mybtis,用的是spring 的jdbc;

  業務需求:給應用添加領域(一個領域包含多個應用,一個應用可能屬於多個領域,一般而言一個應用只屬於一個領域),要求是給應用添加領域的時候,先將該應用已有的領域都刪除,之後再將選中的領域添加到資料庫;

  為了減少準備工作,我利用了以前的代碼和數據建模,那麼就成了:添加person的時候先刪除已存在name為新添加person的name的person,再添加新person,說直白點就是:添加name為zhangsan的person,那麼先刪除資料庫中name為zhangsan的所有person信息,然後再將新的zhangsan的person信息添加到資料庫中;

  環境搭建過程我就不寫了,完整代碼會以附件形式上傳;

  註意:druid連接池一般而言,jdbc設置成自動提交,不設置的話,預設也是自動提交(有興趣的朋友可以去看下druid連接池的源碼)

 

jdbcTemplate自動提交

  先來驗證下,當前jdbcTempalte是否是自動提交的,如何驗證了,我可以在jdbcTemplate執行完之後拋出一個異常,代碼如下  

public int deleteOnePerson(String name) {
        int count = jdbcTemplate.update(DELETE_ONE_PERSON, new Object[]{name});        // jdbcTemplate執行完成
        count = count / 0;                                                            // 拋出RuntimeException
        return count;
    }

  沒有配置事務

<?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/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd">
     
    <context:component-scan base-package="com.lee.you.jdbc" />

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
                   <value>mysqldb.properties</value>
        </property>
    </bean>

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本屬性 url、user、password -->  
        <property name="driverClassName" value="${jdbc.driverClassName}" />  
        <property name="url" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
        <property name="initialSize" value="${jdbc.initialSize}" />  
        <property name="minIdle" value="${jdbc.minIdle}" />   
        <property name="maxActive" value="${jdbc.maxActive}" />  
        <property name="maxWait" value="${jdbc.maxWait}" />
        <!-- 超過時間限制是否回收 -->
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
        <!-- 超過時間限制多長; -->
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
        <!-- 用來檢測連接是否有效的sql,要求是一個查詢語句-->
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <!-- 申請連接的時候檢測 -->
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
        <!-- 申請連接時執行validationQuery檢測連接是否有效,配置為true會降低性能 -->
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
        <!-- 歸還連接時執行validationQuery檢測連接是否有效,配置為true會降低性能  -->
        <property name="testOnReturn" value="${jdbc.testOnReturn}" />
        
        <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}" />
    </bean>

     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
View Code

 

                                                                   

  那麼如果直接像如下方式來處理先刪後加是不行的,如果刪成功添加失敗,那麼資料庫的數據卻只是刪了而沒有添加成功

public int insertOnePerson(String name, int age) {
        int result = 0;
        int count = jdbcTemplate.update(DELETE_ONE_PERSON, new Object[]{name});
        if(count >= 0)                                                                    // =0的情況是資料庫之前不存在該name的person信息
        {
            result = jdbcTemplate.update(INSERT_ONE_PERSON, new Object[]{name,age});
        }
        return result    ;
    }

 

手動提交事務

  為了保證事務一致性,第一時間想到了jdbcTemplate是否有事務相關設置,然而並沒有發現,但是發現了jdbcTemplate.getDataSource().getConnection(),於是飛快的寫瞭如下代碼:

  手動提交1

public int insertOnePerson(String name, int age) {
        int result = 0;
        try {
            jdbcTemplate.getDataSource().getConnection().setAutoCommit(false);
            int count = jdbcTemplate.update(DELETE_ONE_PERSON, new Object[]{name});
            if(count >= 0)                                                                    // =0的情況是資料庫之前不存在該name的person信息
            {
                result = jdbcTemplate.update(INSERT_ONE_PERSON, new Object[]{name,"1ac"});
            }
            jdbcTemplate.getDataSource().getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                jdbcTemplate.getDataSource().getConnection().rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                jdbcTemplate.getDataSource().getConnection().setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result    ;
    }

  本以為實現事務一致性,可執行結果如下:                                        

                                                    

   發現沒有實現事務一致性,這是為什麼??????? 這裡先留個懸念,大家好好思考下;當時我也沒去仔細研究,因為完成任務才是第一要緊事,緊接著寫出瞭如下代碼:

  手動提交2

public int insertOnePerson(String name, int age) {
        int result = 0;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = jdbcTemplate.getDataSource().getConnection();
            if(conn != null)
            {
                conn.setAutoCommit(false);
                pstmt = conn.prepareStatement(DELETE_ONE_PERSON);
                pstmt.setString(1, name);
                int count = pstmt.executeUpdate();
                pstmt.close();
                if(count >= 0)
                {
                    pstmt = conn.prepareStatement(INSERT_ONE_PERSON);
                    pstmt.setString(1, name);
                    pstmt.setString(2, "1adh");                                        // 引發異常
                    result = pstmt.executeUpdate();
                }
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                System.out.println("rollback failed..");
                e1.printStackTrace();
            }
        } finally {
            try{
                conn.setAutoCommit(true);
                if(pstmt != null){
                    pstmt.close();
                }
                if(conn != null){
                    conn.close();
                }
            }catch(SQLException e){
                
            }
        }
        return result    ;
    }

   詭異的事情來了,居然和上面的情況一樣:刪除成功,添加失敗! 我的天老爺,這是怎麼回事????

                           

  瞬間懵逼了,怎麼回事?代碼怎麼改都不行!!!

  mysql引擎

    查看資料庫引擎,發現引擎是MyISAM!  瞬間爆炸!!!!

                                                              

  將引擎改成InnoDB後,手動提交2的代碼是能夠保證事務一致性的,那麼手動提交1的代碼是不是也能保證事務一致性了? 此處再留一個懸念,希望各位觀眾老爺們好好思考下。

 

事務自動管理

  任務雖然完成了,可是無論是手動提交2,還是手動提交1(姑且認為能保證事務一致性),代碼的try catch簡直讓人無法接受;映像中,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: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/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd">
     
    <context:component-scan base-package="com.lee.you.jdbc" />

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
                   <value>mysqldb.properties</value>
        </property>
    </bean>

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本屬性 url、user、password -->  
        <property name="driverClassName" value="${jdbc.driverClassName}" />  
        <property name="url" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
        <property name="initialSize" value="${jdbc.initialSize}" />  
        <property name="minIdle" value="${jdbc.minIdle}" />   
        <property name="maxActive" value="${jdbc.maxActive}" />  
        <property name="maxWait" value="${jdbc.maxWait}" />
        <!-- 超過時間限制是否回收 -->
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
        <!-- 超過時間限制多長; -->
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
        <!-- 用來檢測連接是否有效的sql,要求是一個查詢語句-->
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <!-- 申請連接的時候檢測 -->
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
        <!-- 申請連接時執行validationQuery檢測連接是否有效,配置為true會降低性能 -->
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
        <!-- 歸還連接時執行validationQuery檢測連接是否有效,配置為true會降低性能  -->
        <property name="testOnReturn" value="${jdbc.testOnReturn}" />
        
        <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}" />
    </bean>

     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
View Code

  配置事務

@Transactional
    public int insertOnePerson(String name, int age) {
        int result = 0;
        int count = jdbcTemplate.update(DELETE_ONE_PERSON, new Object[]{name});
        if(count >= 0)                                                                    
        {
            result = jdbcTemplate.update(INSERT_ONE_PERSON, new Object[]{name,"l123a"});
        }
        return result    ;
    }

  執行結果如下:

      

  這代碼清爽多了,要的就是這種感覺!! 就是這個feel倍兒爽,爽爽爽爽!

 

 後話及懸念解答

  搭建這個工程的用到了lombok,不知道的可以去百度下,我這裡就想提醒下,這玩意和一般的jar有區別,他需要安裝,不然編譯不通過! 喜歡搞事的jar;

  另外druid連接池對mysql驅動是有版本要求的,mysql驅動5.1.10是會在連接池初始化的時候報錯的,具體是從哪個版本開始不報錯我就沒去逐個試了,知道的朋友可以留個言,本工程中用的是5.1.25版本;

警告: Cannot resolve com.mysq.jdbc.Connection.ping method.  Will use 'SELECT 1' instead.
java.lang.NullPointerException
    at com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker.<init>(MySqlValidConnectionChecker.java:50)
    at com.alibaba.druid.pool.DruidDataSource.initValidConnectionChecker(DruidDataSource.java:892)
    at com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:608)
    at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:934)
    at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:930)
    at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:102)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:386)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:471)
    at com.lee.you.jdbc.dao.impl.DaoImpl.queryAllPerson(DaoImpl.java:31)
    at com.lee.you.jdbc.JdbcTemplateTest.main(JdbcTemplateTest.java:17)
View Code

  懸念解答

    還記得是哪兩個懸念嗎?  1、手動提交1不能保證事務一致性是不是mysql引擎引起的;  2、如果mysql引擎是支持事務的InnoDB,手動提交1能不能保證事務一致性;

    關於懸念1,這個很明瞭,如果mysql引擎不支持事務,那麼代碼無論怎麼寫,事務一致性都是空談;

    懸念2的話,是能肯定的回答:不能保證事務一致性的! 因為jdbcTemplate.getDataSource().getConnection()獲取的connection與每次jdbcTemplate.update用到的connection都是從連接池中獲取的,不能保證是一個connection,那怎麼保證事務一致性; 感興趣的朋友可以去閱讀源碼,裡面各種黃金、各種美女哦!

  那麼問題又來了,既然jdbcTemplate每次執行一個操作的時候都是從連接池中獲取connection,那麼spring事務管理是怎麼實現事務一致性的呢?更多精彩內容,請關註我的下篇博客

  本文附件


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 2016-12-03 數組定義字元串: 每次定義數組的時候,系統都會在記憶體開闢你指定數組大小的空間,並且數組中的內容對於我們是可讀可寫的,看如下代碼: 1 #include<stdio.h> 2 int main() 3 { 4 char str[100] = "hello world"; 5 ch ...
  • 原文:http://www.cnblogs.com/imaker/p/6128049.html 所屬年份:2010.9;2012.3編寫函數fun,其功能是:根據以下公式求π的值(要求精度0.0005,即某項小於0.0005時停止迭代)。 程式運行後,若輸入精度0.0005,則程式應輸出為3.14… ...
  • 如下是作業,用python做一個ftp,主要利用socket。 server端在linux下運行,在client端可以執行shell命令(靜態的) 在client端輸入get xxx,即可下載。 在client端輸入put xxx,即可上傳。 server端: client端: ...
  • 1.簡化Java開發 Spring是一個開源框架,它的根本使命在於簡化java開發。為了降低java開發的複雜性,Spring採取了以下4種關鍵策略: 1.基於POJO的輕量級和最小侵入性編程; 有很多框架強迫應用繼承它們的類或實現它們的介面從而導致應用與框架綁死,而基於Spring構建的應用通常沒 ...
  • STL的pair,有兩個值,可以是不同的類型。 template struct pair; 註意,pair在頭文件utility中,不要include。(一個錯誤是 include ) 成員類型 first_type first的類型 second_type second的類型 成員變數 first... ...
  • 解釋如下: content 中需要被替換的就是{}中的參數,array數組中存放的是對應的要替換的參數;使用MessageFormat方法的時候,需要要將這些參數的個數匹配正確,並且數序要指定,否則匹配出錯。這樣就實現了參數的替換。很簡單,也很死板。 MessageFormat:出自java.tex ...
  • 在所有編程語言領域,我想字元串應該是地球上最常用的表達手段了吧。 在java的世界里,String是作為類出現的,核心的一個域就是一個char數組,內部就是通過維護一個不可變的char數組,來向外部輸出的。 這是jdk一段String類定義,首先類是final,表明類不可被繼承;核心域是privat ...
  • 1.package 的用途,解決了什麼問題 提供類的命名空間,解決類的命名衝突,類文件管理問題 2.使用舉例 2.1 自測代碼 (1) package 必須做為源文件的第一條非註釋語句 (2) 一個源文件只能有一個包 (3) 沒有顯示指定則處於預設包下 (4) 同包下可自由訪問 1 package ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...