Search code examples
hibernatespring-data-jpaspring-data

Spring Data JPA batch insert or update doesn't work


I have configured hibernate batch configs

    spring.jpa.properties.hibernate.jdbc.batch_size = 20
    spring.jpa.properties.hibernate.order_inserts = true
    spring.jpa.properties.hibernate.order_updates = true
    spring.jpa.properties.hibernate.generate_statistics=true

When saveAll() is called, it generates as many statements, as the list contains entities.

Metrics

    5702800 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    19521800 nanoseconds spent preparing 111 JDBC statements;
    462709900 nanoseconds spent executing 109 JDBC statements;
    85106100 nanoseconds spent executing 7 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    290977000 nanoseconds spent executing 1 flushes (flushing a total of 110 entities and 109 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)

Code

List<TaskImage> taskImages = TASK_ID_TO_IMAGE_MAPPER.apply(entityIds,      pollInfo.getLastPollDate());

return taskImageRepository.saveAll(taskImages);

Hibernate show-sql is enabled, and in consol it shows allone-by-one statements.

NOTE: Mapping also inserts primary keys, and it's not auto-generated.

I know that I can do it using Spring Data JDBC, but want to overcome it using Spring Data JPA.


Solution

  • The answer is that it's actually working correctly. Those queries are SELECT queries, as the data already exist in DB, hibernate merge operation is called and a dirty check mechanism runs.