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

Alo*_*lok 2 java orm batch-processing jpa-2.0

例:

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

现在,让我们说位置和部门是已经具有完整数据的主表。现在,我需要通过JPA插入1000名员工列表。我也与员工表中的位置和部门有关系。

所以现在在执行以下操作后将条目插入到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...
Run Code Online (Sandbox Code Playgroud)

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

WPr*_*cht 5

JPA 2.0不为批处理插入提供特定支持。遵循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();
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用em.createNativeQuery()并启动本机SQL批处理插入。

根据您所使用的特定数据库和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)。

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