Spring › JPA

Comparing JPA IDENTITY, SEQUENCE, and JDBC batch inserts

Benchmarking 100k-row inserts across JPA IDENTITY, pooled SEQUENCE, JdbcTemplate batchUpdate, and driver batch-rewrite options on PostgreSQL and MySQL.

Comparing JPA IDENTITY, SEQUENCE, and JDBC batch inserts

A migration job moving 100,000 club activity logs into a new table took over 100 seconds, even with hibernate.jdbc.batch_size enabled. I traced why Hibernate never batched a single insert, then measured wall-clock time and actual SQL statement counts across ID strategies and JDBC driver rewrite options.

Tested with Spring Boot 3.5.6, Hibernate ORM 6.6.29.Final, Kotlin 2.2.20, JDK 21, PostgreSQL 17.6 (pgjdbc 42.7.7), and MySQL 8.4.6 (Connector/J 9.4.0) on a personal workstation (12 cores, 32GB RAM, Windows + Docker Desktop/WSL2). Each row has 4 columns (100-byte payload), flushed and cleared every 1,000 rows. Numbers show the median of 3 runs after 1 warmup.

The problem

Our migration job for club attendance and activity events looked ordinary: it called Spring Data JPA’s saveAll with Hibernate batching enabled in application.yml.

1
2
3
4
5
6
7
8
# src/main/resources/application.yml
spring:
  jpa:
    properties:
      hibernate:
        jdbc.batch_size: 1000
        order_inserts: true
        generate_statistics: true

Even with those settings in place, inserting 100,000 rows took a median of 104,123ms. Turning on Hibernate session statistics showed zero JDBC batches had executed:

1
2
3
51730123 nanoseconds spent preparing 100000 JDBC statements;
102535297069 nanoseconds spent executing 100000 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;

Root cause

The entity used GenerationType.IDENTITY. With IDENTITY, the database assigns the primary key only after the INSERT runs. Because Hibernate’s persistence context must track every managed entity by its ID immediately after persist(), it can’t queue the insert for transactional write-behind—it executes one INSERT immediately on every persist() call. hibernate.jdbc.batch_size never gets a chance to apply. On my local Docker setup, each database round trip took about 1ms; 100,000 sequential round trips added up directly to 104 seconds.

The SEQUENCE strategy solves this because Hibernate fetches IDs via nextval before running INSERT, letting it buffer inserts into batches. However, leaving allocationSize = 1 still triggers one nextval round trip per row. Matching allocationSize = 1000 on the entity with increment by 1000 on the database sequence lets Hibernate’s pooled optimizer claim 1,000 IDs in memory per sequence call.

The final bottleneck sits in the JDBC driver. Standard JDBC batching sends statements together over the network, yet the database server still executes 1,000 individual INSERT statements. Enabling pgjdbc’s reWriteBatchedInserts=true collapses those into multi-row VALUES (...), (...) statements. Inspecting pg_stat_statements showed each 1,000-row batch split into seven 128-row statements plus one 64-row, one 32-row, and one 8-row statement—pgjdbc prepares power-of-two batch sizes so it can reuse prepared statements across chunks.

The fix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// build.gradle.kts
plugins {
    id("org.springframework.boot") version "3.5.6"
    id("io.spring.dependency-management") version "1.1.7"
    kotlin("jvm") version "2.2.20"
    kotlin("plugin.spring") version "2.2.20"
    kotlin("plugin.jpa") version "2.2.20"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    runtimeOnly("org.postgresql:postgresql")
    runtimeOnly("com.mysql:mysql-connector-j")
}
1
2
3
4
5
# src/main/resources/application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/lab?reWriteBatchedInserts=true
    # MySQL: jdbc:mysql://localhost:3306/lab?rewriteBatchedStatements=true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/main/kotlin/lab/Entities.kt
package lab

import jakarta.persistence.*
import java.time.Instant

@Entity
@Table(name = "event_pooled")
class PooledEvent(
    val userId: Long,
    val type: String,
    val payload: String,
    val createdAt: Instant,
) {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "event_pooled_gen")
    // The DB sequence must also be created with `increment by 1000`
    @SequenceGenerator(name = "event_pooled_gen", sequenceName = "event_pooled_id_seq", allocationSize = 1000)
    var id: Long? = null
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/main/kotlin/lab/BulkWriter.kt
package lab

import jakarta.persistence.EntityManager
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.sql.Timestamp
import java.time.Instant

@Service
class BulkWriter(private val em: EntityManager, private val jdbc: JdbcTemplate) {
    private val createdAt = Instant.parse("2025-10-01T00:00:00Z")
    private val payload = "p".repeat(100)

    // Flush and clear every 1,000 rows to bound persistence context memory
    @Transactional
    fun <T : Any> jpaSaveAll(repo: JpaRepository<T, Long>, n: Int, factory: (Long, String, String, Instant) -> T) {
        (0 until n).chunked(1000).forEach { chunk ->
            repo.saveAll(chunk.map { factory((it % 1000).toLong(), "CLICK", payload, createdAt) })
            em.flush()
            em.clear()
        }
    }

    @Transactional
    fun jdbcBatch(table: String, n: Int) {
        jdbc.batchUpdate(
            "insert into $table (user_id, type, payload, created_at) values (?, ?, ?, ?)",
            (0 until n).toList(), 1000,
        ) { ps, i ->
            ps.setLong(1, (i % 1000).toLong())
            ps.setString(2, "CLICK")
            ps.setString(3, payload)
            ps.setTimestamp(4, Timestamp.from(createdAt))
        }
    }
}

Benchmark results

Here are the 100,000-row results on PostgreSQL. “Server INSERT calls” comes from pg_stat_statements.calls, and batch counts come from Hibernate session statistics.

ApproachMedian timeServer INSERT callsnextval callsJDBC batches
JPA IDENTITY104,123ms100,000-0
JPA SEQUENCE allocationSize=153,928ms100,000100,000100
JPA SEQUENCE pooled 1000851ms100,000100100
JPA SEQUENCE pooled 1000 + rewrite610ms1,000100100
JdbcTemplate batchUpdate776ms100,000--
JdbcTemplate batchUpdate + rewrite320ms1,000--

I ran the same test on MySQL 8.4. Because MySQL doesn’t have native sequences, I compared JPA IDENTITY against JdbcTemplate and tracked server-side insert counts using the Com_insert status variable delta.

Approach (MySQL)Rewrite offRewrite onCom_insert (rewrite on)
JPA IDENTITY60,564ms60,313ms100,000
JdbcTemplate batchUpdate55,424ms938ms100

Without rewriteBatchedStatements=true, Connector/J sent even batchUpdate calls one statement at a time—which explains why it ran almost as slowly as IDENTITY. Turning rewrite on packed 1,000 rows into a single multi-row INSERT, cutting Com_insert down to 100. By contrast, JPA IDENTITY never creates a JDBC batch in the first place, so the driver flag made zero difference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "type": "bar",
  "data": {
    "labels": ["JPA IDENTITY", "JPA SEQ alloc 1", "JPA SEQ pooled", "JdbcTemplate"],
    "datasets": [
      { "label": "PostgreSQL rewrite off", "data": [104123, 53928, 851, 776], "backgroundColor": "#f7768e" },
      { "label": "PostgreSQL rewrite on", "data": [null, null, 610, 320], "backgroundColor": "#9ece6a" },
      { "label": "MySQL rewrite off", "data": [60564, null, null, 55424], "backgroundColor": "#e0af68" },
      { "label": "MySQL rewrite on", "data": [60313, null, null, 938], "backgroundColor": "#7aa2f7" }
    ]
  },
  "options": {
    "plugins": { "title": { "display": true, "text": "Median time for 100,000 inserts (ms, log scale)" } },
    "scales": { "y": { "type": "logarithmic", "title": { "display": true, "text": "ms" } } }
  }
}

Switching from IDENTITY to a pooled SEQUENCE sped up PostgreSQL inserts by 122x on its own, and adding driver batch rewriting cut server-side INSERT statements by 100x. For the Kotlin entity setup (all-open and no-arg compiler plugins), I followed the conventions documented in my post on Kotlin JPA entity design.

Selection guide and checklist

ScenarioRecommended approach
Single-row saves from user requestsIDENTITY is fine (difference isn’t noticeable)
Thousands to tens of thousands of rows needing entity events or cascadesPooled SEQUENCE + batch_size + driver rewrite
Hundreds of thousands of rows, plain ingestion without entity logicJdbcTemplate.batchUpdate + driver rewrite
Multi-million-row initial loadsEvaluate PostgreSQL COPY or MySQL LOAD DATA

When not to use JPA for bulk inserts: if you don’t need entity lifecycle callbacks, auditing listeners, or cascading associations and just want to append rows, the persistence context only adds overhead. Also avoid migrating a live production table from IDENTITY to SEQUENCE just for one batch job—aligning the sequence start value without ID collisions carries operational risk. Splitting that single write path onto JdbcTemplate is safer and faster.

Watch out for two edge cases. First, if @SequenceGenerator(allocationSize = ...) doesn’t match the database sequence’s increment by, Hibernate’s pooled optimizer hands out overlapping or widely gapped ID ranges. Second, enabling reWriteBatchedInserts=true changes the row-count array returned by executeBatch(): individual row counts become Statement.SUCCESS_NO_INFO (-2). In a 5-row test batch, disabling rewrite returned [1, 1, 1, 1, 1], while enabling it returned [-2, -2, -2, -2, 1]. Audit any code that sums executeBatch() return values to count inserted rows.

  • Did Hibernate session statistics confirm JDBC batches is greater than 0?
  • Does the bulk-inserted entity avoid GenerationType.IDENTITY?
  • Do allocationSize and the database sequence increment by match?
  • Is reWriteBatchedInserts=true (PostgreSQL) or rewriteBatchedStatements=true (MySQL) enabled in the JDBC URL?
  • Are you flushing and clearing the EntityManager every ~1,000 rows to keep heap usage bounded?
This post is licensed under CC BY 4.0 by the author.