Skip to content
javahacks.dev
Hibernate

How to Use Hibernate StatelessSession for Bulk Work

Use Hibernate StatelessSession to import and export large data sets without a persistence context, with JDBC batching, scrollable queries and the trade-offs.

6 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, Spring Boot, OpenJDK and MariaDB logos.

A typical Hibernate Session is built for business transactions: load a few entities, change them, commit. It tracks everything it touches in a persistence context, takes a snapshot of each entity to detect changes at flush time and keeps all of it in memory until the session closes. Feed it a million rows and the heap fills with entities and snapshots long before the work is done. That is not a bug; it is the cost of the features. StatelessSession removes the features and the cost. This post shows how to use it for imports and exports, how to batch, what you lose and how it differs from the usual alternatives. For the persistence context itself, Hibernate entity states and the persistence context is the background.

What it does and does not do

FeatureSessionStatelessSession
First level cacheYesNo
Dirty checkingYesNo; call update explicitly
Cascading to associationsYesNo
Lazy loadingYesNo; fetch explicitly
Event listeners and interceptorsYesMostly bypassed
Memory grows with rows touchedYesNo
Statement per operationDeferred to flushImmediate, or batched

Every operation maps to one SQL statement at the point you call it. insert(entity) writes an INSERT, update(entity) writes an UPDATE of all columns whether or not anything changed and delete(entity) deletes. There is nothing to flush and nothing to clear.

Opening one in Spring Boot

Spring Data repositories use the normal EntityManager, so for bulk work you drop to the SessionFactory. Hibernate 6.3 and later provide helpers that open a stateless session, run a block in a transaction and close it:

src/main/java/dev/javahacks/importer/ProductImporter.javajava
package dev.javahacks.importer;

import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductImporter {
    private final SessionFactory sessionFactory;

    public ProductImporter(EntityManagerFactory emf) {
        this.sessionFactory = emf.unwrap(SessionFactory.class);
    }

    public void importAll(Iterable<ProductRow> rows) {
        sessionFactory.inStatelessTransaction(session -> {
            for (ProductRow row : rows) {
                session.insert(new Product(row.sku(), row.name(), row.priceCents()));
            }
        });
    }
}

inStatelessTransaction begins a transaction on a fresh connection, runs the lambda, commits on success and rolls back on an exception. Note that it does not join a Spring @Transactional transaction: it takes its own connection from the pool. That is usually what you want for a batch job, but it means you should not call it from inside another transactional method and expect one atomic unit.

Enable batching

By default each insert is a separate round trip. Batching sends them in groups, which is where most of the speed comes from. Turn it on in the configuration:

src/main/resources/application.propertiesproperties
spring.jpa.properties.hibernate.jdbc.batch_size=500
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

Batching has a catch that surprises people: it does not work with GenerationType.IDENTITY, because Hibernate needs the generated key straight after each insert and cannot defer it. Use a sequence with an allocation size, as in sequence generators and batch inserts:

java
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_seq")
@SequenceGenerator(name = "product_seq", sequenceName = "product_seq", allocationSize = 500)
private Long id;

On PostgreSQL the JDBC driver can also rewrite batched inserts into a multi row statement if you add reWriteBatchedInserts=true to the JDBC URL, which reduces round trips again.

Batched inserts in Hibernate 7

Hibernate 6.5 and later offer an API that inserts many entities in a single call and applies the batch size itself:

java
sessionFactory.inStatelessTransaction(session -> {
    List<Product> batch = new ArrayList<>(500);
    for (ProductRow row : rows) {
        batch.add(new Product(row.sku(), row.name(), row.priceCents()));
        if (batch.size() == 500) {
            session.insertMultiple(batch);
            batch.clear();
        }
    }
    if (!batch.isEmpty()) {
        session.insertMultiple(batch);
    }
});

insertMultiple is the same as calling insert in a loop with batching on, but it states the intent and lets Hibernate group the work. Chunking the input yourself keeps memory flat: the list never holds more than 500 entities.

Streaming a large export

The read side is where a normal session fails worst. List<Product> all = query.getResultList() loads every row. With a stateless session you can stream results one at a time, and because there is no persistence context, nothing accumulates:

java
public void exportCsv(Writer out) {
    sessionFactory.inStatelessSession(session -> {
        try (var rows = session.createSelectionQuery("from Product p order by p.id", Product.class)
                .setFetchSize(1000)
                .getResultStream()) {
            rows.forEach(p -> write(out, p));
        }
    });
}

setFetchSize(1000) asks the JDBC driver to fetch rows in chunks of a thousand. On PostgreSQL the driver only honours it when autocommit is off, which inStatelessSession inside a transaction takes care of; without it the driver buffers the whole result in memory regardless of what you ask. JDBC fetch size and large result sets covers that trap in detail. MySQL needs a fetch size of Integer.MIN_VALUE or useCursorFetch=true to stream.

Updating without dirty checking

Because nothing is tracked, changing a loaded entity does nothing until you say so:

java
sessionFactory.inStatelessTransaction(session -> {
    try (var products = session.createSelectionQuery("from Product p where p.category = :c", Product.class)
            .setParameter("c", "books").getResultStream()) {
        products.forEach(p -> {
            p.applyDiscount(10);
            session.update(p);        // explicit; there is no flush to notice the change
        });
    }
});

Each update writes every column. If the change can be expressed as a single statement, a bulk update Product p set p.price = p.price * 0.9 where p.category = 'books' is usually faster than looping at all, see bulk updates and deletes in JPA.

Associations

Without cascade or lazy loading, relationships are your responsibility. To insert an order line you need the order's key, and you set it yourself. You can reference an existing row without loading it by building an entity with just the id:

java
OrderLine line = new OrderLine();
line.setOrder(session.getReference(PurchaseOrder.class, orderId));   // proxy by id, no select
line.setSku("BK-1");
session.insert(line);

A to-one association is a plain field, and a collection is not loaded unless you call session.fetch(order.getLines()), which Hibernate 6.3 added for this purpose. Design import code in terms of rows and foreign keys, and it fits the stateless model naturally.

Alternatives

ApproachMemorySpeedNotes
Normal Session with flush() and clear() every N rowsBoundedGoodKeeps lifecycle callbacks; easy to get wrong
StatelessSessionFlatGoodFewest moving parts for bulk
JdbcClient or JdbcTemplate.batchUpdateFlatBestNo entities; you write the SQL, see JDBC batch updates
COPY (PostgreSQL) or LOAD DATA (MySQL)FlatFastestDatabase specific, bypasses everything

The first option is worth knowing, because it needs no new API: inside one session, call entityManager.flush() and entityManager.clear() every few hundred rows to release the persistence context. It works, but you must remember to do it, and it keeps the dirty checking cost for the entities currently in memory.

Choosing the batch size

The batch size is a trade-off between round trips and memory. Very small batches, say 10, keep memory trivial and make many network calls; very large ones, tens of thousands, reduce round trips and can exceed driver packet limits or hold large statements in memory. A value between 200 and 1,000 is a sensible start for rows of ordinary size. Test with your real rows, watch the time per thousand rows as you change the value and stop when the curve flattens. On PostgreSQL, reWriteBatchedInserts often matters more than the exact batch size, so test with and without it.

When this does not apply

Do not use a stateless session for ordinary request handling. Without dirty checking and cascades, the code you write is more error prone, and you lose lifecycle callbacks, so auditing annotations such as @CreatedDate that rely on listeners may not fire. If the data volume is a few thousand rows, a normal session with batching is simpler and fast enough. If an import is dominated by validation or transformation, its cost is Java time, not Hibernate. For the reference, read the Hibernate user guide on StatelessSession and the PostgreSQL JDBC driver notes on cursors.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.