【问题标题】:Batch update with Spring data jpa使用 Spring 数据 jpa 进行批量更新
【发布时间】:2019-05-02 10:50:30
【问题描述】:

我正在尝试批量更新表格。 以下是我的配置:

spring.jpa.properties.org.hibernate.flushMode=COMMIT
spring.jpa.properties.hibernate.jdbc.batch_size=10
spring.jpa.properties.hibernate.order_inserts=true 
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.org.hibernate.SQL=DEBUG
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.generate_statistics=true
spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true

以下是实际使用的方法:

    @Transactional(propagation=Propagation.REQUIRES_NEW)
public void updateEmployeeDetails(Map<String, List<String>> orgEAMap) {
    ....
    updateEmployee(employeeMap);
}


public void updateEmployee(Map<String, String> employeeMap) {
    //int i =0;
    for (Entry<String, String> mapEntry : employeeMap.entrySet()) {
        Query query = em.createNativeQuery("UPDATE employee emp SET emp.name = :name WHERE emp.id = :id");
        query.setParameter("id", mapEntry.getValue());
        query.setParameter("name", mapEntry.getKey());
        query.executeUpdate();
        //if(i==10){
            //LOG.info("Flushmode"+em.getFlushMode());
            //em.flush();
        //}
        //i++;
    }
}

我尝试在某个计数后手动刷新,但在每次查询执行后刷新(部分刷新)已经发生。 从统计日志中,我可以看到有 10 个语句正在创建,0 个批处理和刷新正在发生。

【问题讨论】:

    标签: hibernate jpa spring-data-jpa batch-processing updates


    【解决方案1】:

    Hibernate 的批处理配置会影响实体及其更改的处理方式。显式查询会立即执行。

    如果您想使用批处理,我看到两个选项:

    1. 实际加载实体,更改要更新的属性,然后让 Hibernate 完成。当然,这会增加加载实体的额外开销,这可能是不希望的。
    2. 直接使用数据源使用 SQL,侧步 EntityManager。我建议为此使用 spring 模板。

    注意:您可能还需要更新版本属性以避免丢失更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2021-08-13
      • 2014-11-14
      • 2020-03-15
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多