使用 Spring 数据 jpa 批量更新
Batch update with Spring data jpa
我正在尝试批量更新 table。
以下是我的配置:
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 的批处理配置会影响实体及其更改的处理方式。显式查询立即执行。
如果您想使用批处理,我看到两个选项:
- 实际加载实体,更改您要更新的属性,然后让 Hibernate 来做这件事。当然,这会产生加载实体的额外开销,这可能是不希望的。
- 使用 SQL 直接使用数据源,避开
EntityManager
。我建议为此使用 spring 模板。
注意:您可能还想更新版本属性以避免丢失更新。
我正在尝试批量更新 table。 以下是我的配置:
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 的批处理配置会影响实体及其更改的处理方式。显式查询立即执行。
如果您想使用批处理,我看到两个选项:
- 实际加载实体,更改您要更新的属性,然后让 Hibernate 来做这件事。当然,这会产生加载实体的额外开销,这可能是不希望的。
- 使用 SQL 直接使用数据源,避开
EntityManager
。我建议为此使用 spring 模板。
注意:您可能还想更新版本属性以避免丢失更新。