简体   繁体   English

我可以使用Spring Data saveAll()方法和Hibernate 5批处理吗?

[英]Can I use Spring Data saveAll() method and Hibernate 5 batch?

I have a Spring boot application with application.yml : 我有一个带有application.yml的Spring Boot应用application.yml

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        url: *my_url*
        password: *my_pass*
        username: *my_username*
    jpa:
        properties:
            hibernate:
                jdbc:
                    batch_size: 15
                    #order_inserts: true
                    #order_updates: true
                    #batch_versioned_data: true

When I try to save 200 000 entities using the method saveAll(Iterable<S> entities) , it saves all 200 000 entities at the same time, but I want to save batches of 15 entities at a time. 当我尝试使用方法saveAll(Iterable<S> entities)保存20万个实体时,它同时保存了所有20万个实体,但是我想一次保存15个实体的批次。

Is it possible to use Spring Data's SimpleJpaRepository and Hibernate's batch? 是否可以使用Spring Data的SimpleJpaRepository和Hibernate的批处理?

My approach )) 我的方法

@Service
public class BulkService {

    @PersistenceContext
    private EntityManager em;

    // @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}")
    private int batchSize = 20;

    private List<Entity> savedEntities;

    public Collection<Entity> bulkSave(List<Entity> entities) {
        int size = entities.size();
        savedEntities = new ArrayList<>(size);

        try {
            for (int i = 0; i < size; i += batchSize) {
                int toIndex = i + (((i + batchSize) < size) ? batchSize : size - i);
                processBatch(entities.subList(i, toIndex));
                em.flush();
                em.clear();
            }
        } catch (Exception ignored) {
            // or do something...  
        }
        return savedEntities;
    }

    @Transactional
    protected void processBatch(List<Entity> batch) {

        for (Entity t : batch) {
            Entity result;
            if (t.getId() == null) {
                em.persist(t);
                result = t;
            } else {
                result = em.merge(t);
            }
            savedEntities.add(result);
        }
    }
}

Working example and test 工作实例测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM