Sub topic 14
JDBC batching for inserts and updates
The earlier chapters in this tutorial reduced the number of SELECT statements. Writes have a similar cost. By default Hibernate sends one INSERT or UPDATE per row, and each statement is a separate network round trip to the database. This chapter shows how to group those statements into JDBC batches, and which mappings stop batching from working.
It assumes you know the persistence context and flushing from the earlier chapters, and basic @Entity and @Id mapping. It also assumes you have run a Spring Boot application against a real database such as PostgreSQL or MySQL.
Why batching helps
Suppose you import 1,000 authors. Without batching, the application makes 1,000 round trips. Each round trip costs network latency plus statement parsing on the server. With a batch size of 50, Hibernate hands the JDBC driver 50 statements at a time. The driver sends them together, so the import takes about 20 round trips.
The gain grows with latency between the application and the database. It is small on localhost and large against a managed cloud database.
Enabling batching
Batching is off by default. These three properties turn it on:
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true| Property | Effect |
|---|---|
| `hibernate.jdbc.batch_size` | Maximum number of statements sent in one JDBC batch. Values between 20 and 100 are common. |
| `hibernate.order_inserts` | Sorts pending inserts by entity type so that statements for the same table are adjacent. |
| `hibernate.order_updates` | Does the same for updates, and also orders by primary key. This reduces the chance of deadlocks between concurrent transactions. |
Ordering matters because a JDBC batch can only contain statements with identical SQL text. If you persist an Author, then a Book, then an Author, and so on, each switch of table ends the current batch. With ordering enabled, Hibernate sorts the queue so that all author inserts run first.
Some drivers need an extra setting before they send real batches. PostgreSQL needs reWriteBatchedInserts=true on the JDBC URL, which rewrites a batch into a multi-row INSERT. MySQL needs rewriteBatchedStatements=true. Without these, the driver may still send the statements one at a time inside a batch call.
The identity generator disables insert batching
Hibernate has to know a row's primary key before it can treat the entity as managed. With GenerationType.IDENTITY, only the database knows the key, and it only produces it when the row is inserted. Hibernate therefore executes the INSERT immediately at persist(), and nothing is left to batch.
Use a sequence instead. Hibernate can then reserve a block of ids with one sequence call and assign them in memory:
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "author_seq")
@SequenceGenerator(name = "author_seq", sequenceName = "author_seq", allocationSize = 50)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
protected Author() {
}
public Author(String name) {
this.name = name;
}
public void rename(String newName) {
this.name = newName;
}
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}The allocationSize must equal the INCREMENT BY value of the database sequence. If the two differ, Hibernate may hand out duplicate ids or skip large ranges. If you let Hibernate generate the schema, it creates the sequence with the matching increment. If you manage the schema with Flyway or Liquibase, write create sequence author_seq start with 1 increment by 50 yourself.
Not every database offers sequences. MySQL had none before MariaDB added them, and its AUTO_INCREMENT columns behave like IDENTITY. On MySQL you can use a table-based generator, which batches but adds contention on the generator table. Alternatively, accept that inserts will not batch.
Batching inserts in a loop
Enabling the properties is not enough for large imports. Every persisted entity stays in the persistence context until the transaction ends, so 100,000 inserts keep 100,000 objects in memory, and dirty checking scans all of them at each flush. The standard pattern is to flush and clear in chunks that match the batch size:
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuthorImportService {
private static final int BATCH_SIZE = 50;
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void importAuthors(List<String> names) {
int count = 0;
for (String name : names) {
entityManager.persist(new Author(name));
count++;
if (count % BATCH_SIZE == 0) {
entityManager.flush();
entityManager.clear();
}
}
}
}Each flush() sends one JDBC batch of 50 inserts. The clear() detaches the entities, so memory use stays flat. The final partial chunk is flushed when the transaction commits.
clear() also detaches every other entity you loaded in this transaction. Do not hold on to those references and expect changes to them to be saved.
JpaRepository.saveAll() calls save() for each element inside one transaction. It does batch when the properties are set and the id generator allows it. It does not flush or clear, so for very large imports use the loop above.
Batching updates
Updates work through dirty checking. You load entities, change fields, and Hibernate emits an UPDATE for each changed entity at flush time. With batch_size set, those UPDATEs are grouped, and order_updates sorts them so identical statements are adjacent.
The same memory concern applies, so process the data in pages and clear between them:
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuthorMaintenanceService {
private final AuthorRepository authorRepository;
@PersistenceContext
private EntityManager entityManager;
public AuthorMaintenanceService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void appendSuffix(String suffix) {
int pageNumber = 0;
Page<Author> page;
do {
page = authorRepository.findAll(PageRequest.of(pageNumber++, 50, Sort.by("id")));
page.forEach(author -> author.rename(author.getName() + suffix));
entityManager.flush();
entityManager.clear();
} while (page.hasNext());
}
}Sorting by id keeps the page boundaries stable. Renaming does not change the sort key, so no rows are skipped or repeated.
If the change is the same for every row, you do not need entities at all. A single JPQL or native update statement runs in one round trip and bypasses the persistence context. The trade-off is that it ignores @Version checks and lifecycle callbacks, and any entities already loaded become stale.
Other things that stop a batch
- Mixed statement types. A batch holds one kind of statement. Interleaved inserts into different tables, such as an author followed by its books, split batches unless
order_insertsis on. - Versioned entities. With
@Version, Hibernate must check that each UPDATE affected exactly one row. Current Hibernate versions support this inside batches throughhibernate.jdbc.batch_versioned_data, which defaults to true. Very old drivers may report unknown update counts. Then Hibernate cannot verify them. - Cascades that trigger selects.
persistwithCascadeType.ALLis fine.merge()on detached entities issues a SELECT per entity first, which is another N+1 on the write side. Preferpersist()for new rows. - Large rows. Batches of rows with big LOB columns can use a lot of driver memory. Lower the batch size in that case.
Verifying that batching works
SQL logging shows each statement as Hibernate prepares it, even when the driver later sends them in one batch. A log of 50 INSERT lines therefore does not prove that batching failed. To see real batches, turn on statistics and log the session metrics:
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.engine.internal.StatisticalLoggingSessionEventListener=INFOAt the end of each session, Hibernate logs a line such as executing 20 JDBC batches next to the count of JDBC statements. Twenty batches for 1,000 inserts means batching is active. A figure close to 1,000 means something is blocking it, most often an IDENTITY id or a missing driver setting.
For a stricter check, use a datasource proxy library that logs batch sizes at the JDBC level, and assert on them in an integration test as the previous chapter did for read queries.
Exercise
You set hibernate.jdbc.batch_size=50 and import 5,000 authors with persist() in a loop. The Author id uses GenerationType.IDENTITY. The session metrics report roughly 5,000 JDBC statements and no batches. What is the cause, and what two changes fix it and keep memory use bounded?
Show answer
IDENTITY ids are only known after the row is inserted, so Hibernate runs each INSERT immediately at persist() and has nothing to queue. Switch to GenerationType.SEQUENCE with a @SequenceGenerator whose allocationSize equals the database sequence increment (for example 50). Also flush() and clear() the EntityManager every 50 entities so the persistence context does not grow with the whole import. Setting order_inserts=true helps when several entity types are inserted together.