Video in progress

Strong Middle 🌱 Spring

When is Hibernate's StatelessSession useful for bulk import or processing, and how does it differ from a regular Session?

StatelessSession works without a persistence context: no first-level cache, no dirty checking, no cascades, no lazy loading, and every insert/update becomes SQL immediately. Memory doesn't grow on a million-row import and it is faster, but you give up the JPA conveniences.

📖 Answer

If you import 1 million rows with a regular Session, every object you persist stays in the persistence context. Unless you flush() + clear() every 1000 or so, you get OutOfMemoryError, and even if you do, dirty checking runs on every flush.

StatelessSession removes that load:

@Service
class TariffImporter {
    private final EntityManagerFactory emf;
    // ... constructor

    void importAll(Stream<TariffRow> rows) {
        SessionFactory sf = emf.unwrap(SessionFactory.class);
        try (StatelessSession s = sf.openStatelessSession()) {
            Transaction tx = s.beginTransaction();
            rows.forEach(r -> s.insert(Tariff.from(r)));
            tx.commit();
        }
    }
}

What you lose:

  • cascade: you insert the children separately yourself;
  • lazy loading: you load the associations you need in the query yourself;
  • dirty checking: you say explicitly what changed with update(entity);
  • entity listeners and Spring Data auditing: don't assume they work, check in your version;
  • it doesn't automatically join Spring's @Transactional: as above, it opens its own connection and transaction. So on an error you handle the rollback yourself too.

When I pick it: big imports/exports, one-off data migrations, ETL, meaning there is almost no domain logic and data is just being moved. Where there are business rules and cascades, committing in batches with a regular Session is better.

Often bypassing JPA completely is an option too: JdbcTemplate.batchUpdate or PostgreSQL COPY turn out to be the fastest and simplest for this kind of job. I measure those first.