1.网上最常见的JPA----entityManager批量操作方法
private EntityManager em; @PersistenceContext(name = "EntityManagerFactory") public void SetEntityManager(EntityManager em) { this.em = em; } @Transactional public void saveBatch(List<CustomerEntity> list) { for (int i = 0; i < 10000; i++) { em.persist(list.get(i)); if (i % 1000 == 0) { em.flush(); em.clear(); } } }
2.Jpa--Repository批量写入
@Transactional public void saveBatchJpa(List<CustomerEntity> list) { repository.save(list); }
3.结论
EM和JPA直接操作集合没有太大的性能区别,直接使用JPA操作集合即可。如下是JPA操作集合的代码,可以看出起始内部也是用的em
@Transactional public <S extends T> List<S> save(Iterable<S> entities) { List<S> result = new ArrayList<S>(); if (entities == null) { return result; } for (S entity : entities) { result.add(save(entity)); } return result; } /* * (non-Javadoc) * @see org.springframework.data.repository.CrudRepository#save(java.lang.Object) */ @Transactional public <S extends T> S save(S entity) { if (entityInformation.isNew(entity)) { em.persist(entity); return entity; } else { return em.merge(entity); } }