JPA 2.0:如何通过JPA提高批量插入的性能 [英] JPA 2.0: How to improve performance on bulk insertion through JPA

查看:4289
本文介绍了JPA 2.0:如何通过JPA提高批量插入的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

我有三个表:位置,部门,员工

I have three tables: location, department, employee

现在可以说位置和部门是已有完整数据的主表。
现在我需要通过JPA插入1000个Employees列表。
我也与员工表中的位置和部门有关系。

now lets say location and department are master tables which already has whole data. Now I need to insert 1000 Employees list through JPA. I have relationship with Location and department in Employee Table as well.

所以现在在Employee中插入条目,我正在做:

so now to insert the entry in Employee, following I am doing:

for loop...1000
 Employee e = new Employee();
 e.setId(12);
 e.setEmpname("ABC");
 Location l = null;
 l = em.find(Location.class, 234);
 e.setLocation(l);
  Department d = null;
 d = em.find(Department.class, 111);
 e.setDepartment(d);
 em.persist(e);
loop ends...

将数据加载到DB需要一些时间。它是通过JPA插入数据的唯一方法,因为它会降低性能。
我不想使用本机查询。
请建议是否有人有更好的方法来提高效率。

It's taking some time to load the data into DB. Is it the only way to insert the data through JPA, as it is slowing down the performance. I don't want to use native queries. Please suggest if anybody have better approach to make it more efficient.

推荐答案

JPA 2.0不提供具体的支持用于批量插入。保持在JPA惯用语中,你可以这样做:

JPA 2.0 doesn't provide specific support for batch inserts. Keeping within the JPA idiom, you can do this:

EntityManager em = ...;
EntityTransaction tx = em.getTransaction();
tx.begin();

for (int i = 0; i < 100000; i++) {
    Employee e = new Employee();
    // setup entity
    em.persist(e);
    if ((i > 0) && (i % 20 == 0)) { // Flush in batches of 20 to keep caches from bogging.
        em.flush();
        em.clear();
    }
}

tx.commit();
session.close();

或者,您可以使用em.createNativeQuery()并触发本机SQL批量插入。

Or, you can use em.createNativeQuery() and fire off a native SQL batch insert.

根据您使用的特定数据库和ORM,还有其他几种可能性。例如,EclipseLink有一些技巧( http://java-persistence-performance.blogspot.com/2011/06/how-to-improve-jpa-performance-by-1825.html )或参数化( http://java-persistence-performance.blogspot.com/2013 /05/batch-writing-and-dynamic-vs.html )。

There are several other possibilities depending on the specific database and ORM you are using. For instance there are tricks with EclipseLink (http://java-persistence-performance.blogspot.com/2011/06/how-to-improve-jpa-performance-by-1825.html) or parametrization (http://java-persistence-performance.blogspot.com/2013/05/batch-writing-and-dynamic-vs.html).

可以在此处找到Hibernate特定的演练: http://korhner.github.io/hibernate/hibernate-performance-traps-part- 2 /

A Hibernate specific walk-through can be found here: http://korhner.github.io/hibernate/hibernate-performance-traps-part-2/

这篇关于JPA 2.0:如何通过JPA提高批量插入的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆