简体   繁体   English

JPA 2.0:如何通过JPA提高批量插入的性能

[英]JPA 2.0: How to improve performance on bulk insertion through JPA

Example: 例:

I have three tables: location, department, employee 我有三个表:位置,部门,员工

now lets say location and department are master tables which already has whole data. 现在,让我们说位置和部门是已经具有完整数据的主表。 Now I need to insert 1000 Employees list through JPA. 现在,我需要通过JPA插入1000名员工列表。 I have relationship with Location and department in Employee Table as well. 我也与员工表中的位置和部门有关系。

so now to insert the entry in Employee, following I am doing: 所以现在在执行以下操作后将条目插入到Employee中:

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...

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. 这是通过JPA插入数据的唯一方法,因为它会降低性能。 I don't want to use native queries. 我不想使用本机查询。 Please suggest if anybody have better approach to make it more efficient. 请建议是否有人有更好的方法来提高效率。

JPA 2.0 doesn't provide specific support for batch inserts. JPA 2.0不为批处理插入提供特定支持。 Keeping within the JPA idiom, you can do this: 遵循JPA习惯用法,您可以执行以下操作:

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();

Or, you can use em.createNativeQuery() and fire off a native SQL batch insert. 或者,您可以使用em.createNativeQuery()并启动本机SQL批处理插入。

There are several other possibilities depending on the specific database and ORM you are using. 根据您所使用的特定数据库和ORM,还有其他几种可能性。 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 ). 例如,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 )。

A Hibernate specific walk-through can be found here: http://korhner.github.io/hibernate/hibernate-performance-traps-part-2/ 可以在这里找到特定于Hibernate的演练http : //korhner.github.io/hibernate/hibernate-performance-traps-part-2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM