1:先看hibernate的批量更新处理。

版本背景:hibernate 5.0.8

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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.yugh.test.mvc">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 属性文件位置 -->
    <bean id="annotationPropertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:init.properties</value>
            </list>
        </property>
    </bean>
    <!-- 配置数据源 c3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 请求超时时间 -->
        <property name="checkoutTimeout" value="30000" />
        <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
        <property name="idleConnectionTestPeriod" value="30" />
        <!-- 连接数据库连接池最大空闲时间 -->
        <property name="maxIdleTime" value="30" />
        <!-- 连接池初始化连接数 -->
        <property name="initialPoolSize" value="5" />
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
        <property name="acquireIncrement" value="5" />
    </bean>
    <!-- 配置hibernate的SessionFactory -->
     <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入数据源 相关信息看源码 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 扫描hibernate注解 -->
        <property name="packagesToScan" value="org.yugh.test.mvc" />
        <!-- hibernate配置信息 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <!-- 开启二级缓存 ehcache -->
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
                </prop>
            </props>
        </property>
    </bean> 

    <!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> -->
        <!-- Spring处理方式 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

    <!-- Spring处理方式 -->

    <!-- <aop:aspectj-autoproxy proxy-target-class="true"/>
    <aop:config proxy-target-class="true">
        <aop:pointcut id="pointcut" expression="execution(* org.yugh.test.mvc.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
    <context:component-scan base-package="org.yugh.test.mvc" />
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean> -->

    <!-- Spring处理方式 -->

    <!-- 支持  @Transactional 标记 -->
     <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- 配置事务增强处理Bean,指定事务管理器 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <!-- 配置详细事务处理语义 -->
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
            <!-- 其他采用默认事务方式 -->
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
    <!-- Spring aop事务管理 -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="transactionPointcut" expression="execution(* org.yugh.test.mvc.services.*.*(..))" />
        <!--  指定在txAdvice切入点应用txAdvice事务增强处理-->
        <aop:advisor pointcut-ref="transactionPointcut"    advice-ref="transactionAdvice" />
    </aop:config> 

    <!-- redis工厂 -->
    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" />
    <!-- p:host-name="172.20.22.4" p:port="6379" p:password="" -->
    <!-- redis服务封装 -->
    <bean id="redisServer" class="org.yugh.test.mvc.redis.RedisServer">
    </bean>
</beans>

主要事务用的hibernate。

DAO层封装代码:

 @Resource
  private SessionFactory sessionFactory;
  /**
* 获取当前工作的Session */ protected Session getSession() { return sessionFactory.getCurrentSession(); }

业务层DAO大致代码:

   public int updateForHibernateTest(List<Object> list){
	Transaction transaction = getSession().beginTransaction();
	Long  beTime = System.currentTimeMillis();
	String sql = "update t_sale_order_ty_temp a set a.taker_name=?,a.taker_phone=?,a.pay_time=sysdate where a.order_id=? ";
	Query query = getSession().createSQLQuery(sql);
	    for (int i = 0; i < list.size(); i++) {
		query.setParameter(0, "yugh");
		query.setParameter(1, "批量提交更新");
		query.setParameter(2, list.get(i));
		query.executeUpdate();
	      }
	  //transaction.commit();
	    Long enTime = System.currentTimeMillis();
	    System.out.println("结束时间,共计花费:" + String.valueOf( (enTime - beTime)/1000 ) + " 秒!" );
	    return query.getMaxResults();
}

解释:list<object>的list就是取order_id的字段来批量更新 taker_name和 taker_phone值,pay_time字段是记录是否同步批量提交。

这种写法每次循环去更新一条,最原始的update方式,一秒5条数据左右。

好处:很容易和项目融合,弊端:慢。

10793条数据更新时间:

Hibernate: update t_sale_order_ty_temp a set a.taker_name=?,a.taker_phone=?,a.pay_time=sysdate where a.order_id=?
结束时间,共计花费:48 秒!
17:37:14,061  INFO GenericApplicationContext:960 - Closing org.springframework.context.support.GenericApplicationContext@18eed359: startup date [Mon Oct 23 17:36:22 CST 2017]; root of context hierarchy

  

2:再看spring的批量提交处理。

版本背景:spring 4.2.5

变动applicationContext.xml 配置清单中有一条:

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

个人觉得spring的jdbctemplate可简可繁,属于小型、大型项目都可以随时拿来用的。

业务层DAO大致代码:

public int updateForSpring(final List<Object> list) {
	String sql = "update t_sale_order_ty_temp a set a.taker_name=?,a.taker_phone=?,a.pay_time=sysdate where a.order_id=? ";
	long beTime = System.currentTimeMillis();
	jdbcTemplate.batchUpdate(sql.toString(), new BatchPreparedStatementSetter() {
		@Override
		public void setValues(PreparedStatement pstmt, int i) throws SQLException {
			pstmt.setString(1, "yugh");
			pstmt.setString(2, "批量提交更新");
			pstmt.setString(3, list.get(i)+"");
		}

		@Override
		public int getBatchSize() {
			return list.size();
		}
	});
	long enTime = System.currentTimeMillis();
	System.out.println("批量更新结束,共计花费时间:" + String.valueOf( (enTime - beTime) /1000 ) + " 秒!" );
	return list.size();
}

解释:list<object>的list就是取10793条数据的order_id字段来批量更新 taker_name和 taker_phone值,pay_time字段是记录是否同步批量提交。

通过执行10793条数据后得出同步批量更新的数据。

好处:很容易和项目融合,代码精短。

10793条数据更新时间:

Hibernate: select order_id from t_sale_order_ty_temp where 1=1
批量更新结束,共计花费时间:20 秒!
17:52:37,912  INFO GenericApplicationContext:960 - Closing org.springframework.context.support.GenericApplicationContext@370736d9: startup date [Mon Oct 23 17:52:14 CST 2017]; root of context hierarchy

本文只介绍批量更新,批量insert和批量delete相比要简单多,事务和性能上也没有批量更新注意得多。

  

Spring批量更新batchUpdate提交和Hibernate批量更新executeUpdate的更多相关文章

  1. hibernate批量更新和删除数据

    批量处理  不建议用Hibernate,它的insert效率实在不搞,不过最新版本的Hibernate似乎已经在批量处理的时候做过优化了,设置一些参数如batch_size,不过性能我没有测试过,听说 ...

  2. Hibernate批量处理数据

    01.批量插入数据 步骤一.创建实体类,Dept和Emp /** * 员工类 * @author Administrator * */ public class Emp { private Integ ...

  3. Hibernate批量处理海量数据的方法

    本文实例讲述了Hibernate批量处理海量数据的方法.分享给大家供大家参考,具体如下: Hibernate批量处理海量其实从性能上考虑,它是很不可取的,浪费了很大的内存.从它的机制上讲,Hibern ...

  4. hibernate 批量增加 修改 删除

    4.2  Hibernate的批量处理 Hibernate完全以面向对象的方式来操作数据库,当程序里以面向对象的方式操作持久化对象时,将被自动转换为对数据库的操作.例如调用Session的delete ...

  5. hibernate 批量插入数据

    如题,有两种方法 1)使用FLUSH 2)使用JDBC 分别来解释: 1)hibernate在进行数据库操作的时候,都要有事务支持的.可能你曾遇到过,没有加事务,程序会报错的情况. 而事务每次提交的时 ...

  6. mybatis批量增、删、改(更新)操作oracle和mysql批量写法小记

    前言:用mybatis也好几年了,mybatis在批量的增删操作也写起来也是比较简单的,只有批量更新这一块是特别坑,特此记录. 注:本文主要用来记录oracle和mysql数据库在使用mybatis的 ...

  7. Hibernate批量抓取

    ------------------siwuxie095 Hibernate 批量抓取 以客户和联系人为例(一对多) 1.批量抓取 同时查询多个对象的关联对象,是 Hibernate 抓取策略的一种 ...

  8. Hibernate 批量update数据时,怎么样做可以回滚,

    Hibernate 批量update数据时,怎么样做可以回滚, 1.serviceManagerDaoImpl代码里对异常不进行try,catch抛出, 2.或者抛出throw new Runtime ...

  9. 多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中【我】

    多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中 package com.xxx.xx.reve.service; import java.util.ArrayL ...

随机推荐

  1. 201521123112《Java程序设计》第14周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 关系型数据库系统:使用表来存储数据,使用行来区分不同记录. 主键可以唯一确定一条记录. 常见的数据库管理系统有: ...

  2. JS中有关分支结构、循环结构以及函数应用的一些简单练习

    案例一:搬桌子    年龄大于七岁男女都可以搬桌子,年龄小于七岁大于五岁的男生可以搬桌子: var num =parseInt(prompt("请输入你的年龄")) var sex ...

  3. JS运算符的一些简单练习和应用

    练习-01    判断奇数偶数           var num =prompt("请输入一个数");                                    al ...

  4. Mybatis第六篇【配置文件和映射文件再解读、占位符、主键生成与获取、Mapper代理】

    配置文件和映射文件再解读 映射文件 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象,mapper.xml以statement为单位管理 ...

  5. 关于APP分享到QQ、微信等

    <script> var shares=null;        var Intent=null,File=null,Uri=null,main=null; function plusRe ...

  6. 交互模式下测试python代码及变量的四则运算

    在交互模式下,python代码可以立即执行,所以这很方便我们进行代码测试 1.命令窗口,输入python (如果没配置环境变量则需带python安装目录的绝对路径) >>> 这个就是 ...

  7. css左右布局的几种实现方式和优缺点

    记录一下左右布局的实现方式,实现的具体效果是,左侧固定宽度,高度适中等于父元素的高度,父元素的高度由右侧内容决定: html代码如下: <div class="parent" ...

  8. Vi快捷操作 vim配置【shell文件格式从windows转换为linux】

    vim配置 http://www.cnblogs.com/ma6174/archive/2011/12/10/2283393.html gg 首行 dd 删除当前行 :.,$d  删除全部内容 :se ...

  9. 使用LayUI展示数据

    LayUI是一款免费,开源,轻量级的前端cms框架,适用于企业后端,能快速上手开发,集成了常用的组件,还有完善的文档和社区. 点击查看 文档地址 下载框架 使用: 1.把这个5个文件项都拷贝到项目中 ...

  10. An Introduction to Variational Methods (5.1)

    在这篇文章中,我引用Bishop书中的一个例子,来简单介绍一下Variational Methods的应用.想要更详细地理解这个例子,可以参考Bishop的书Pattern Recongnition ...