前言

  项目框架主要是spring,持久层框架没有用mybtis,用的是spring 的jdbc;

  业务需求:给应用添加领域(一个领域包含多个应用,一个应用可能属于多个领域,一般而言一个应用只属于一个领域),要求是给应用添加领域的时候,先将该应用已有的领域都删除,之后再将选中的领域添加到数据库;

  为了减少准备工作,我利用了以前的代码和数据建模,那么就成了:添加person的时候先删除已存在name为新添加person的name的person,再添加新person,说直白点就是:添加name为zhangsan的person,那么先删除数据库中name为zhangsan的所有person信息,然后再将新的zhangsan的person信息添加到数据库中;

  环境搭建过程我就不写了,完整代码会以附件形式上传;

  注意:druid连接池一般而言,jdbc设置成自动提交,不设置的话,默认也是自动提交(有兴趣的朋友可以去看下druid连接池的源码)

  路漫漫其修远兮,吾将上下而求索!

  github:https://github.com/youzhibing

  码云(gitee):https://gitee.com/youzhibing

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>

  那么如果直接像如下方式来处理先删后加是不行的,如果删成功添加失败,那么数据库的数据却只是删了而没有添加成功

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>

  配置事务

@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)

  悬念解答:

    还记得是哪两个悬念吗?  1、手动提交1不能保证事务一致性是不是mysql引擎引起的;  2、如果mysql引擎是支持事务的InnoDB,手动提交1能不能保证事务一致性;

    关于悬念1,这个很明了,如果mysql引擎不支持事务,那么代码无论怎么写,事务一致性都是空谈;

    悬念2的话,是能肯定的回答:不能保证事务一致性的! 因为jdbcTemplate.getDataSource().getConnection()获取的connection与每次jdbcTemplate.update用到的connection都是从连接池中获取的,不能保证是一个connection,那怎么保证事务一致性; 感兴趣的朋友可以去阅读源码,里面各种黄金、各种美女哦!

  那么问题又来了,既然jdbcTemplate每次执行一个操作的时候都是从连接池中获取connection,那么spring事务管理是怎么实现事务一致性的呢?更多精彩内容,请上车

  本文附件

spring jdbcTemplate 事务,各种诡异,包你醍醐灌顶!的更多相关文章

  1. 【Spring】事务(transactional) - REQUIRES_NEW在JdbcTemplate、Mybatis中的不同表现

    环境 数据库: oracle 11g JAR: org.springframework:spring-jdbc:4.3.8.RELEASE org.mybatis:mybatis:3.4.2 概念 R ...

  2. jdbcTemplate事务管理

    1.基于TransactionTemplate的编程式事务管理 Spring之路(39)–基于TransactionTemplate的编程式事务管理 本篇通过TransactionTemplate类, ...

  3. SpringBoot系列: JdbcTemplate 事务控制

    ============================Spring JdbcTemplate 事务控制============================之前使用 JDBC API 操作, 经常 ...

  4. Spring JdbcTemplate 与 事务管理 学习

    Spring的JDBC框架能够承担资源管理和异常处理的工作,从而简化我们的JDBC代码, 让我们只需编写从数据库读写数据所必需的代码.Spring把数据访问的样板代码隐藏到模板类之下, 结合Sprin ...

  5. Spring jdbctemplate和事务管理器 全注解配置 不使用xml

    /** * spring的配置类,相当于bean.xml */@Configuration//@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans ...

  6. Spring(四)Spring JdbcTemplate&声明式事务

    JdbcTemplate基本使用 01-JdbcTemplate基本使用-概述(了解) JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装.spr ...

  7. 开涛spring3(9.3) - Spring的事务 之 9.3 编程式事务

    9.3  编程式事务 9.3.1  编程式事务概述 所谓编程式事务指的是通过编码方式实现事务,即类似于JDBC编程实现事务管理. Spring框架提供一致的事务抽象,因此对于JDBC还是JTA事务都是 ...

  8. 【学习笔记】Spring JdbcTemplate (3-3-3)

    Spring与JDBC模板(jdbcTemplate) 为了避免直接使用JDBC而带来的复杂冗长的代码 Spring提供的一个强有力的模板类 -- jdbcTemplate简化JDBC操作 并且数据源 ...

  9. Hibernate与Spring的事务管理

    什么是事务 这个问题比较大,按照我的理解就是,一个事务内的n个操作,要么全部完成,一旦有一个操作有问题,那么所有的操作都全部回滚. Jdbc的事务 首先,大家已经知道了,事务说白了就是一个词----统 ...

随机推荐

  1. python模块:subprocess

    # subprocess - Subprocesses with accessible I/O streams # # For more information about this module, ...

  2. Lambda表达式遍历和泛型ForEach遍历方式

    lambda表态式 DataTable dtAllItems = policySecurity.GetUserAccessTypeOnAllItems(userID); List<DataRow ...

  3. OPC转发阿里云alink工具

    这个最近还在做 2019-04-24 今天抽空吧基本mqtt上传,OPC遍历,导出物模型功能先做了 上报操作日志,上报错误信息,导入参数,导出参数还没做 有需要可以联系微信NBDX123

  4. Spring使用Autowiring自动装配 解决提示报错小技巧

    1.打开Settings   输入Inspections  找到Spring --> Spring Core --> Code --> Autowiring  for  Bean  ...

  5. OpenXml修改word特定内容

    采用OpenXml来修改word特定内容,如下: word: OpenXml修改word之前: OpenXml修改word之后: 代码: string path = @"C:\Users\A ...

  6. Python之路【第三篇】编码

    Python代码——>字节码——>机器码——>计算机 Windows: cmd ==> python 文件路径 cmd ==>python >> 输入命令 L ...

  7. SVN完全备份,增量备份,库同步

    svn备份一般采用三种方式:1)svnadmin dump 2)svnadmin hotcopy 3)svnsync. 优缺点分析: ============== 第一种svnadmin hotcop ...

  8. Python学习笔记-函数基础

    函数基础 定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 为什么使用函数:减少重复代码.使程序变的可扩展使程序变得易维护 1.定义一个函数 #定 ...

  9. UniGui中使用Grid++Report报表控件子报表获取数据的方法

    Grid++Report是为优秀的报表控件,子报表是其重要功能之一,但Grid++Report提供的网页报表示范主要是以页面为主的,UniGui在Delphi中以快速编写web管理软件著称,但由于资料 ...

  10. Redis-06.Cluster

    Redis Cluster是一个高性能高可用的分布式系统.由多个Redis实例组成的整体,数据按照一致性哈希算法存储分布在多个Redis实例上,并对使用虚拟槽(Slot)对一致性哈希算法进行改进,通过 ...