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

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

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

@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);
}

字符串

3pvhb19x

3pvhb19x1#

这是修改后的代码,

@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++) {
         Object primaryKeyObj = this.getPrimaryKey(list.get(i));
             //Using find as it will make entity managed.
        T entityObject = list.get(i);
            Object found = entityManager.find(entityObject.getClass(), primaryKeyObj);
            if(found!=null) {

                entityManager.merge(entityObject);
        } else{
        entityManager.persist(entityObject);
        }   
            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);
}

字符串

相关问题