2015-08-18 62 views
1

例子:JPA 2.0:如何通過JPA提高批量插入性能

我有三個表:位置,部門,員工

現在可以說,位置和部門都已經有完整的數據主表。 現在我需要通過JPA插入1000個員工列表。 我與員工表中的位置和部門也有關係。

所以現在插入在員工中的條目,下面我做:

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

它需要一些時間將數據加載到數據庫。它是通過JPA插入數據的唯一方式,因爲它會降低性能。 我不想使用原生查詢。 如果有人有更好的方法來提高效率,請提出建議。

+1

進行刷新,並明確在兩者之間持續存在的X號。否則由於髒檢查它會變得越來越慢。 –

回答

4

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

或者,你可以使用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/