JPA批量操作及性能比对
假设需要批量插入10000条实体数据至数据库。如下是各个操作方法及耗时
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
@Autowiredprivate JdbcTemplate jdbcTemplate;public void jdbc(List<String> list){int[] updatedCountArray=jdbcTemplate.batchUpdate("INSERT INTO customer (name) VALUES (?);", new BatchPreparedStatementSetter() {@Overridepublic void setValues(PreparedStatement preparedStatement, int i) throws SQLException {preparedStatement.setString(1,list.get(i));}@Overridepublic int getBatchSize() {return list.size();}});}
package net.xjdsz.model;import javax.persistence.*;/*** Created by dingshuo on 2017/6/23.*/@Entity@Table(name = "customer", schema = "test", catalog = "")public class CustomerEntity {private int id;private String name;@Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name = "id", nullable = false)public int getId() {return id;}public void setId(int id) {this.id = id;}@Basic@Column(name = "name", nullable = true, length = 100)public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;CustomerEntity that = (CustomerEntity) o;if (id != that.id) return false;if (name != null ? !name.equals(that.name) : that.name != null) return false;return true;}@Overridepublic int hashCode() {int result = id;result = 31 * result + (name != null ? name.hashCode() : 0);return result;}}
private EntityManager em;@PersistenceContext(name = "EntityManagerFactory")public void SetEntityManager(EntityManager em) {this.em = em;}@Transactionalpublic void saveBatch(List<CustomerEntity> list) {for (int i = 0; i < 10000; i++) {em.persist(list.get(i));if (i % 1000 == 0) {em.flush();em.clear();}}}
package net.xjdsz.dao;import net.xjdsz.model.CustomerEntity;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;/*** Created by dingshuo on 2017/6/23.*/@Repositorypublic interface CustomerRepository extends JpaRepository<CustomerEntity,Integer> {}
@Transactionalpublic void saveBatchJpa(List<CustomerEntity> list) {repository.save(list);}
package net.xjdsz;import net.xjdsz.dao.CustomerRepository;import net.xjdsz.dao.TestService;import net.xjdsz.model.CustomerEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.List;/*** Created by dingshuo on 2017/6/23.*/@RestControllerpublic class TestController {@AutowiredTestService service;//测试用的Service类@AutowiredCustomerRepository repository; //实体Repository接口@GetMapping(value = "/test")public void test(){List<String> list=new ArrayList<>(); //给jdbctemplate用的集合List<CustomerEntity> customerEntityList=new ArrayList<>();//给jpa用的集合for(int i=0;i<10000;i++){list.add("学生"+i);CustomerEntity customerEntity=new CustomerEntity();customerEntity.setName("学生"+i);customerEntityList.add(customerEntity);}//1.jdbclong startTime=System.currentTimeMillis(); //获取开始时间service.jdbc(list);long endTime=System.currentTimeMillis(); //获取结束时间System.out.println("jdbc程序运行时间: "+(endTime-startTime)+"ms");//2.jpa-emlong startTime1=System.currentTimeMillis(); //获取开始时间service.saveBatch(customerEntityList);long endTime1=System.currentTimeMillis(); //获取结束时间System.out.println("JPA-EM程序运行时间: "+(endTime1-startTime1)+"ms");//3.jpa-循环long startTime2=System.currentTimeMillis(); //获取开始时间for(int i=0;i<customerEntityList.size();i++){repository.save(customerEntityList.get(i));}long endTime2=System.currentTimeMillis(); //获取结束时间System.out.println("JPA-循环程序运行时间: "+(endTime2-startTime2)+"ms");//4.jpa-集合long startTime3=System.currentTimeMillis(); //获取开始时间repository.save(customerEntityList);long endTime3=System.currentTimeMillis(); //获取结束时间System.out.println("JPA-集合程序运行时间: "+(endTime3-startTime3)+"ms");}}
jdbc程序运行时间: 878msJPA-EM程序运行时间: 2018msJPA-循环程序运行时间: 21915msJPA-集合程序运行时间: 2373ms
@Transactionalpublic <S extends T> List<S> save(Iterable<S> entities) {List<S> result = new ArrayList<S>();if (entities == null) {return result;}for (S entity : entities) {result.add(save(entity));}return result;}/** (non-Javadoc)* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)*/@Transactionalpublic <S extends T> S save(S entity) {if (entityInformation.isNew(entity)) {em.persist(entity);return entity;} else {return em.merge(entity);}}
JPA批量操作及性能比对的更多相关文章
- jpa batch批量操作save和persist比较
1.网上最常见的JPA----entityManager批量操作方法 private EntityManager em; @PersistenceContext(name = "Entity ...
- 深入浅出学Spring Data JPA
第一章:Spring Data JPA入门 Spring Data是什么 Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map ...
- JPA基础
目录 目录 1 一.JPA基础 2 1.1 JPA基础 2 1.2JPA开发过程 3 1.3 实体的生命周期及实体管理器常用方法 4 二.环境搭建 5 2.1 添加JPA支持 6 2.2 添加配置文件 ...
- Spring Data Jpa配置
Spring Data JPA提供的接口,也是Spring Data JPA的核心概念: 1:Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组 ...
- JPA && Spring Data && Spring Data JPA
1.JPA Java Persistence API,用于对象持久化的一组API,JPA本身是一组规范,让开发者用同一种方式访问不同的ORM框架.其实也就是java实体对象和关系型数据库建立起映射关 ...
- JPA学习笔记
一.JPA基础1.1 JPA基础JPA: java persistence api 支持XML.JDK5.0注解俩种元数据的形式,是SUN公司引入的JPA ORM规范 元数据:对象和表之间的映射关系 ...
- Spring Boot 系列教程2-Data JPA
Spring Data JPA 用来简化创建 JPA 数据访问层和跨存储的持久层功能. 官网文档连接 http://docs.spring.io/spring-data/jpa/docs/curren ...
- Spring Data JPA 入门Demo
什么是JPA呢? 其实JPA可以说是一种规范,是java5.0之后提出来的用于持久化的一套规范:它不是任何一种ORM框架,在我看来,是现有ORM框架在这个规范下去实现持久层. 它的出现是为了简化现有的 ...
- Spring Data JPA 初体验
一,JPA相关的概念 JPA概述 全称是:JavaPersistence API.是SUN公司推出的一套基于ORM的规范. Hibernate框架中提供了JPA的实现. JPA通过JDK 5.0注解或 ...
随机推荐
- Python3.7.4入门-6/7错误和异常/类
6 错误和异常 while True: try: x = int(input("Please enter a number: ")) break except ValueError ...
- vs code 配置c/c++环境
1. 编译 通过 code-runner插件 运行编译 安装code-runner后在settings.json中找到code-runner.executorMap,可以看到其中的cpp 文件运行方式 ...
- Codeforces Round #197 (Div. 2) A. Helpful Maths【字符串/给一个连加计算式,只包含数字 1、2、3,要求重新排序,使得连加的数字从小到大】
A. Helpful Maths time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...
- PHP队列类
/** * Created by PhpStorm. * User: LAMP-Q哥 * Date: 2017/8/3 * Time: 12:58 */ class Queue { private $ ...
- 如何建一个Liferay 7的theme
首先附上原文链接Creating theme and Deploying in liferay 7 by using Eclipse 1.第一步:建一个Liferay module 项目,选择them ...
- Linux常用命令3 文件搜索命令
文件搜索非常占用资源,所以尽量不要使用这个命令 避免少用该命令最好的方式是设置好文件夹结构,文件不要乱放 1.文件搜索命令:find 命令名称:find 所在路径:/bin/find 执行权限:所有用 ...
- ThinkPHP5.0中报错could not find driver的解决方式
这个报错是我的tp5项目转移到另外的服务器中发生的错误, 其中报错信息中还包含这pdo等字眼 解决方法:在php.ini中开启php_pdp_mysql.dll
- C语言获当地时间
代码如下: #include <stdio.h> #include <time.h> #define DEBUGE 1 int main(void) { time_t rawt ...
- jpa hibernate 打印sql,format日志,打印SQL参数,打印什么指令
环境说明:IntelliJ IDEA 2017.3.4 版本:SpringBoot 2.0.0.RELEASE:hibernate用的是JPA自带. 打印SQL 到控制台: 首先,我使用的是appli ...
- 2018-12-25-win10-uwp-release-因为-Entry-Point-Not-Found-无法启动
title author date CreateTime categories win10 uwp release 因为 Entry Point Not Found 无法启动 lindexi 2018 ...