I'm writing method to update batch using entity manager(Eclipselink as a provider). One approach I found here Batch updates in JPA (Toplink) and here (JPA - Batch/Bulk Update - What is the better approach?) but I'm not using spring Data JPA. If i use JPQL then entity will not be added to cache(is it right.) I'm using following approach. But it is slower one Any other approach I can use ?
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public <T> void updatetBatch(List<T> list) {
if (list == null || list.isEmpty())
throw new NullPointerException();
EntityManager entityManager = entityManagerFactory.createEntityManager();
final int BATCHLIMIT = 50;
try {
int size = list.size();
for (int i = 0; i < size; i++) {
//Using find as it will make entity managed.
Object found=entityManager.find(list.get(i).getClass(), this.getPrimaryKey(list.get(i)));
if(found!=null)
entityManager.merge(list.get(i));
if (i % BATCHLIMIT == 0) {
entityManager.flush();
entityManager.clear();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
}
private Object getPrimaryKey(Object object) {
return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object);
}
Thanks in advanced.