Fastest MS SQL Inserts — Part 5: Hibernate Tuning

Overview

In Part 1 we watched Spring Data's saveAll() take ~12x longer than batched persist() because every entity triggers a SELECT before its INSERT. In Part 2 we switched to raw JDBC and cut the time further. But Hibernate still sits well behind — so how close can it actually get to the bare metal?

Three settings close ~90% of the gap to the raw Bulk Copy API: implement Persistable to kill the pre-INSERT SELECTs (~12x faster saveAll), use StatelessSession to drop the first-level cache (near raw-JDBC speed), and layer useBulkCopyForBatchInsert=true on top (another ~2–3x). Combined with proper batch sizing, this is as fast as Hibernate gets.

Setup: 100,000 Person rows per test, median of 10 runs — Temurin JDK 21, SQL Server 2025 Developer on Ubuntu, i5-4690K pinned to one core at 3.5 GHz (same rig as Part 2). Code in the example repo.

The saveAll Problem: SELECT Before INSERT

When you call repository.saveAll(entities), Spring Data JPA checks each entity's ID. If the ID is non-null, it assumes the entity might already exist and calls EntityManager.merge() — which issues a SELECT before the INSERT. For 100,000 entities, that's 100,000 extra SELECTs.

This only bites when the application assigns the ID — like Person.personId here, which has no @GeneratedValue. With an autogenerated ID, isNew() sees null on a fresh entity and saveAll goes straight to persist(). (Watch the strategy though: IDENTITY generation fetches each key with an immediate INSERT per row — which disables JDBC batching. SEQUENCE batches fine.)

Fix: Implement Persistable

The fix is simple: make your entity implement Persistable<T> and track isNew() yourself — true only until the entity is first persisted or loaded:

 1// imports omitted
 2@Entity
 3@Table(name = "person")
 4public class PersistablePerson implements Persistable<Integer> {
 5    @Id
 6    private int personId;
 7    private String userName;
 8    private String firstName;
 9    private String lastName;
10    private int years;
11
12    @Transient
13    private boolean isNew = true;
14
15    @Override
16    public Integer getId() { return personId; }
17
18    @Override
19    public boolean isNew() { return isNew; }
20
21    @PostPersist
22    @PostLoad
23    void markNotNew() { this.isNew = false; }
24}

When isNew() returns true, Spring Data uses persist() (direct INSERT) instead of merge() (SELECT + INSERT). The @PostPersist and @PostLoad callbacks reset the flag after the entity is saved or loaded from the database.

Results: saveAll ~12x faster

Strategy100k persons (median ms)
saveAll (original, Part 1)26,545
saveAll + Persistable2,140

Persistable makes saveAll ~12x faster. The SELECT elimination is the single biggest win — saveAll now delegates straight to persist(). That also means the batched entityManager.persist() loop from Part 1 (2,064 ms) is the same implementation — just a manual way to reach the identical code path — so it's not listed separately below.

Why does saveAll() fire a SELECT before each INSERT?

StatelessSession: Bare-Metal Hibernate

Hibernate's StatelessSession is designed for bulk operations. It bypasses:

  • First-level cache — no entity state tracking, constant memory
  • Dirty checking — no scanning managed entities at flush time
  • Cascading — related entities must be inserted explicitly
 1// imports and constructor omitted
 2@Repository
 3public class StatelessSessionInsertRepository {
 4    private final EntityManagerFactory entityManagerFactory;
 5
 6    public void insertStateless(List<Person> people) {
 7        SessionFactory sf = entityManagerFactory.unwrap(SessionFactory.class);
 8
 9        try (StatelessSession session = sf.openStatelessSession()) {
10            session.getTransaction().begin();
11
12            for (int i = 0; i < people.size(); i++) {
13                session.insert(people.get(i));
14            }
15
16            session.getTransaction().commit();
17        }
18    }
19}

Results: within ~1% of raw JDBC

Strategy100k persons (median ms)
saveAll (original, Part 1)26,545
saveAll + Persistable2,140
StatelessSession1,850

StatelessSession adds another ~14% on top of the Persistable fix (1,850 vs 2,140 ms) — ~14x faster than the saveAll we started with. No first-level cache, no dirty checking: the per-entity bookkeeping Persistable couldn't remove is gone.

What does StatelessSession drop vs a regular Session? (select all that apply)

When is StatelessSession the wrong tool?

The Killer Combo: StatelessSession + useBulkCopyForBatchInsert

Remember the useBulkCopyForBatchInsert=true connection string parameter from Part 4? It transparently converts PreparedStatement batches to SQL Server's Bulk Copy protocol. It works with StatelessSession too:

StrategyNormalbulkCopy=trueSpeedup
saveAll + Persistable2,1401,0782.0x
StatelessSession1,8506462.9x

StatelessSession + bulkCopy=true = 646 ms — that's ~30% off the raw Bulk API (499 ms), while still using Hibernate's mapping metadata. For applications that need ORM convenience with near-JDBC performance, this is the sweet spot.

Which Hibernate setup hits 646 ms on 100k inserts?

What batch size should you use?

The knob that matters is hibernate.jdbc.batch_size — that's what controls the JDBC batch the driver actually sends. We swept it for every strategy above (100k inserts, median of 10, CPU locked at 3.5 GHz).

The knees — the last batch size that still buys a significant win before gains flatten or regress:

StrategyOptimal batch_sizeMedian ms
saveAll+Persistable1,0002,198
StatelessSession1,0001,896
saveAll+Persistable + bulkCopy1,0001,074
Stateless + bulkCopy5,000638

Two takeaways:

  • Without the flag, batch size barely matters once you're at ~500+. The plain paths sit at ~1.8–2.4 s; round-trips only hurt below ~100 (3.2–3.5 s at 10).
  • With useBulkCopyForBatchInsert, batch size is the tuning knob. Each executeBatch() becomes one bulk-copy stream, so batch_size=10 is the cliff edge: 10,000 tiny streams, ~20 s — slower than batch_size=1, which skips batching entirely. And at bs=1 the flag never engages — no batch, no bulk copy — so all four paths converge to ~14 s unbatched. StatelessSession + bulkCopy bottoms out at ~10,000 (633 ms).

How do these times compare to earlier posts?

Same rig, same 100k scale — the unflagged numbers sit within a few percent of Part 2's October re-benchmark:

Match-up (100k rows, large batch)Earlier postsPart 5Verdict
StatelessSession vs raw JDBCJdbcTemplate 1,873 (Part 2 re-run)1,850within ~1% — ORM tax gone
saveAll + Persistable vs persist()Hibernate persist 2,064 (Part 1 re-run)2,140~4% apart — same code path, as expected
Hibernate + bulkCopy vs raw Bulk APIBulk Copy API 499 (Part 2)646 / 1,078~30% off for StatelessSession, ~2.2x for the regular session

Batch sizes are each post's large-batch optimum (~5,000–10,000); the Bulk API itself wobbles 360–500 ms across runs.

  • StatelessSession really is bare-metal Hibernate. ~1% off JdbcTemplate means the entity-tracking tax is gone — what's left is SQL generation and parameter binding.
  • saveAll + Persistable is persist(). A ~4% gap on identical code is pure run-to-run noise — the delegation does exactly what it promises and nothing more.
  • Raw Bulk API still wins — but barely for Hibernate. StatelessSession + flag comes within ~30% (646 vs 499); the regular session path lands ~2.2x off (1,078). The flag's ~2–3x speedup also matches Part 4, measured there at 1M rows.
  • Part 3's multi-value INSERT still beats the ORM path — ~450 ms at 400 objects per statement, under 646 and using nothing but plain JDBC. It costs you hand-written SQL; StatelessSession keeps the ORM mapping.

The one thing to remember

StatelessSession + useBulkCopyForBatchInsert=true = 646 ms for 100k inserts — ~30% off raw Bulk Copy (499 ms), with ORM mapping metadata still working for you. If you need Hibernate's convenience without paying Hibernate's full price, that's the combination.

If you can only make one change to speed up a saveAll() call: implement Persistable<T> with isNew = true. It eliminates the pre-INSERT SELECTs and makes saveAll ~12x faster — a 10-line code change for a ~12x result.

Test yourself

Which Hibernate features help close the gap to raw JDBC? (select all that apply)

github Browse the example code https://github.com/mmarko88/blog-examples/tree/main/fastest-insert/part5-hibernate-tuning

Open in GitHub Codespaces

💬 Reply

Liked this post?

Follow me on X and LinkedIn for more Java posts like this one.

Comments

Posts in this series

More posts