hibernate 提高批处理更新和与数据库和缓存同步的通用方法的性能

e4yzc0pl  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(147)

我写的方法来更新批处理使用实体管理器(作为一个提供者)。
我在这里找到一种方法:Batch updates in JPA (Toplink)和这里:JPA - Batch/Bulk Update - What is the better approach?
但我没有使用spring Data JPA。如果我使用JPQL,那么实体将不会被添加到缓存中(对吗)。我使用以下方法。但它更慢。还有其他方法可以使用吗?

  1. @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
  2. public <T> void updatetBatch(List<T> list) {
  3. if (list == null || list.isEmpty())
  4. throw new NullPointerException();
  5. EntityManager entityManager = entityManagerFactory.createEntityManager();
  6. final int BATCHLIMIT = 50;
  7. try {
  8. int size = list.size();
  9. for (int i = 0; i < size; i++) {
  10. //Using find as it will make entity managed.
  11. Object found=entityManager.find(list.get(i).getClass(), this.getPrimaryKey(list.get(i)));
  12. if(found!=null)
  13. entityManager.merge(list.get(i));
  14. if (i % BATCHLIMIT == 0) {
  15. entityManager.flush();
  16. entityManager.clear();
  17. }
  18. }
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. } finally {
  22. entityManager.close();
  23. }
  24. }
  25. private Object getPrimaryKey(Object object) {
  26. return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object);
  27. }

字符串

3pvhb19x

3pvhb19x1#

这是修改后的代码,

  1. @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
  2. public <T> void updatetBatch(List<T> list) {
  3. if (list == null || list.isEmpty())
  4. throw new NullPointerException();
  5. EntityManager entityManager = entityManagerFactory.createEntityManager();
  6. final int BATCHLIMIT = 50;
  7. try {
  8. int size = list.size();
  9. for (int i = 0; i < size; i++) {
  10. Object primaryKeyObj = this.getPrimaryKey(list.get(i));
  11. //Using find as it will make entity managed.
  12. T entityObject = list.get(i);
  13. Object found = entityManager.find(entityObject.getClass(), primaryKeyObj);
  14. if(found!=null) {
  15. entityManager.merge(entityObject);
  16. } else{
  17. entityManager.persist(entityObject);
  18. }
  19. if (i % BATCHLIMIT == 0) {
  20. entityManager.flush();
  21. entityManager.clear();
  22. }
  23. }
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. } finally {
  27. entityManager.close();
  28. }
  29. }
  30. private Object getPrimaryKey(Object object) {
  31. return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object);
  32. }

字符串

展开查看全部

相关问题