Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 119 ยท JPA and Hibernate

Hibernate's Native API: Session, HQL and Native SQL

Use Hibernate's native API - Session vs EntityManager, configuration styles, HQL beyond JPQL, native SQL mapping, pagination, query cache, statistics and batch work.

Everything in this chapter so far used the standard Jakarta Persistence API: EntityManager, JPQL and annotations that work with any provider. But most JPA applications run on Hibernate, and Hibernate has its own, older and richer API underneath: SessionFactory and Session, the HQL query language, native SQL with flexible result mapping, a StatelessSession for bulk work, and statistics that tell you exactly what it did. You will meet this API in long-lived code bases, in Hibernate's own documentation, and whenever you need a feature the standard doesn't have.

This lesson maps the native API onto what you already know, compares the three ways to configure Hibernate, and then covers the features that matter in production: HQL extensions, native SQL, pagination pitfalls, the query cache, statistics and fast batch inserts. Hibernate isn't available in our sandbox, so its code is shown read-only. The runnable programs reproduce each mechanism with JDBC and H2, so you can watch the SQL and the number of round trips change. You should know JPQL, fetching and the entity lifecycle first.

Session and SessionFactory vs EntityManager

The native types are not a separate world. Since Hibernate 5.2 they extend the JPA interfaces:

Hibernate Extends (JPA) Lifetime Thread-safe?
SessionFactory EntityManagerFactory one per database, for the whole application yes
Session EntityManager one per unit of work (request, transaction) no
Transaction EntityTransaction one per transaction no
org.hibernate.query.Query / SelectionQuery TypedQuery one per execution no

So a Session is an EntityManager with extra methods, and the persistence context, dirty checking and flushing work identically. You can move between the two worlds at any time:

Java
// from JPA to Hibernate
Session session = entityManager.unwrap(Session.class);
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

// native API in use: inTransaction begins, commits, or rolls back on exception, then closes the session
sessionFactory.inTransaction(session -> {
    Book book = session.find(Book.class, 42L);
    book.setPrice(new BigDecimal("19.90"));              // dirty checking, no save() needed
});

List<Book> cheap = sessionFactory.fromTransaction(session ->
    session.createSelectionQuery("from Book where price < :max", Book.class)
           .setParameter("max", new BigDecimal("10"))
           .getResultList());

Older code uses session.save(), update(), saveOrUpdate() and delete(). These were deprecated in Hibernate 6 and removed in Hibernate 7. Use the JPA-style persist(), merge() and remove() on the session instead, and find() rather than the old get()/load(). If you upgrade an old project, that rename is usually the biggest part of the job.

Which API should new code use? In a Spring Boot application, inject the EntityManager (or use Spring Data) and unwrap(Session.class) only where you need a Hibernate feature. Pure Hibernate applications without Spring often use SessionFactory directly, and that's perfectly fine.

Three ways to configure Hibernate

The same settings can come from three places. Here is one setup written in each style.

hibernate.cfg.xml is Hibernate's own file, read by the native bootstrap new Configuration().configure():

XML
<!-- src/main/resources/hibernate.cfg.xml -->
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/orm/cfg">
    <session-factory>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/shop</property>
        <property name="hibernate.connection.username">shop</property>
        <property name="hibernate.jdbc.batch_size">50</property>
        <property name="hibernate.show_sql">true</property>
        <mapping class="com.example.shop.Book"/>
        <mapping class="com.example.shop.Author"/>
    </session-factory>
</hibernate-configuration>
Java
SessionFactory sessionFactory = new Configuration()
    .configure()                                          // reads hibernate.cfg.xml
    .setProperty("hibernate.connection.password", System.getenv("DB_PASSWORD"))
    .buildSessionFactory();

persistence.xml is the JPA standard, covered in Entities and Hibernate Setup. It defines a named persistence unit, and Persistence.createEntityManagerFactory("shop") reads it. Hibernate-specific settings go in as ordinary <property> elements.

Spring Boot properties replace both files. Boot builds the factory itself, so you only set values; standard settings have spring.jpa.* names, and any other Hibernate setting is passed through with the spring.jpa.properties. prefix:

PROPERTIES
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.generate_statistics=false
hibernate.cfg.xml persistence.xml Spring Boot
Standard Hibernate only Jakarta Persistence Spring
Bootstrap Configuration Persistence automatic
Entities found by <mapping class> <class> (scanning in containers) package scanning
Typical today legacy and plain-Hibernate apps Jakarta EE and plain JPA most new projects

Hibernate 7 also offers a typed, XML-free builder, HibernatePersistenceConfiguration, which extends the JPA 3.2 PersistenceConfiguration with methods such as jdbcUrl(...) and showSql(...).

HQL: JPQL plus Hibernate's extensions

HQL (Hibernate Query Language) is the language Hibernate actually parses; JPQL is a subset of it. Every JPQL query is valid HQL, but HQL accepts much more. A selection of what HQL adds:

Java
// the select clause is optional
session.createSelectionQuery("from Book where price > 20", Book.class);

// limit and offset written in the query itself
session.createSelectionQuery("from Book order by published desc limit 5", Book.class);

// results as maps or lists instead of entities
session.createSelectionQuery("select new map(b.title as title, b.price as price) from Book b", Map.class);

// set operations, CTEs and window functions
session.createSelectionQuery("""
    select b.title, b.price, rank() over (order by b.price desc)
    from Book b
    """, Object[].class);

// insert ... select and insert ... values as mutation queries
session.createMutationQuery("""
    insert into ArchivedBook (id, title)
    select b.id, b.title from Book b where b.published < :cutoff
    """).setParameter("cutoff", LocalDate.of(2000, 1, 1)).executeUpdate();

The native API also separates the two kinds of query: createSelectionQuery only accepts queries that return rows, and createMutationQuery only accepts insert, update and delete, so mixing them up fails at once instead of at runtime later. Beyond queries, the native API brings features with no JPA equivalent, among them natural ids (@NaturalId String isbn plus session.bySimpleNaturalId(Book.class).load("978-..."), cached by key) and filters (@Filter conditions you switch on per session, such as session.enableFilter("activeOnly")).

Pagination, and the trap with collection fetches

Paging works in HQL as in JPQL: setFirstResult(offset) and setMaxResults(size), which Hibernate turns into the database's syntax, such as offset ? rows fetch first ? rows only. Always pair it with an order by on something unique, as Querying with JPQL explains.

The trap appears when you combine paging with a fetch join on a collection. select a from Author a join fetch a.books returns one SQL row per book, so a SQL LIMIT would cut through the middle of an author's books. Hibernate therefore doesn't put the limit in the SQL at all: it loads every matching row and pages in memory, logging warning HHH90003004 ("firstResult/maxResults specified with collection fetch; applying in memory"). With a big table that's a silent memory bomb. Set hibernate.query.fail_on_pagination_over_collection_fetch=true to turn the warning into an exception, and use two queries instead: page the ids, then fetch those authors with their books.

Java Paging authors with their books

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The single LIMIT 2 returns Ama twice and nobody else, because both rows are her books. The two-query version returns exactly two complete authors. In HQL the second query is select a from Author a join fetch a.books where a.id in :ids order by a.id.

Native SQL and result mapping

When HQL isn't enough, session.createNativeQuery(sql, ...) runs your SQL as written. What makes the native API flexible is how it maps the rows:

Java
// 1. Rows as managed entities (the query must return every mapped column)
List<Book> books = session.createNativeQuery("select * from book where price > :min", Book.class)
    .setParameter("min", 20)
    .getResultList();

// 2. Scalar rows as Object[] with explicit types
List<Object[]> rows = session.createNativeQuery("select title, price from book", Object[].class)
    .addScalar("title", StandardBasicTypes.STRING)
    .addScalar("price", StandardBasicTypes.BIG_DECIMAL)
    .getResultList();

// 3. Rows into a record, with a tuple transformer
List<PriceRank> ranks = session.createNativeQuery("""
        select title, price, rank() over (order by price desc) as price_rank from book
        """, Object[].class)
    .setTupleTransformer((tuple, aliases) ->
        new PriceRank((String) tuple[0], (BigDecimal) tuple[1], ((Number) tuple[2]).intValue()))
    .getResultList();

The standard JPA way to map rows to a constructor is @SqlResultSetMapping with @ConstructorResult, declared once on an entity and referenced by name. The tuple transformer does the same in code. Both do what the next program does by hand: read each column by its label and call a record's constructor.

Java Mapping native SQL rows to records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Dune and Beloved share rank 2, and the next rank is 4: that's how RANK() treats ties. Native queries tie your code to one database dialect and Hibernate can't validate them at startup, so keep them for what HQL can't express, and cover each one with an integration test against the real database.

A native query that changes data bypasses the persistence context, just like a bulk HQL update. Hibernate flushes pending changes before running it, but entities already loaded keep their old values. Call session.clear() (or refresh() the affected entities) after native updates.

Statistics and the query cache

You can't tune what you can't measure. With hibernate.generate_statistics=true, Hibernate counts everything it does, and sessionFactory.getStatistics() hands it to you:

Java
Statistics stats = sessionFactory.getStatistics();
log.info("statements={} queries={} entities loaded={} 2LC hits={} query cache hits/misses={}/{}",
    stats.getPrepareStatementCount(), stats.getQueryExecutionCount(), stats.getEntityLoadCount(),
    stats.getSecondLevelCacheHitCount(), stats.getQueryCacheHitCount(), stats.getQueryCacheMissCount());
log.info("slowest query: {} ms: {}", stats.getQueryExecutionMaxTime(), stats.getQueryExecutionMaxTimeQueryString());

Statistics cost a little overhead, so teams turn them on in tests and staging, or expose them through Micrometer and Actuator in production (Actuator and Observability). A test that asserts getPrepareStatementCount() for an important use case catches N+1 regressions before they ship.

The query cache stores the results of a query (the ids of the returned entities, or the scalar values) under a key made of the query text and its parameters. It needs hibernate.cache.use_query_cache=true, a second-level cache provider, and an opt-in per query with .setCacheable(true). Its weak point is invalidation: Hibernate keeps an update timestamp per table, and any insert, update or delete on a table invalidates every cached query that reads that table. The program below implements that mechanism, together with a statement counter like the one in Hibernate's statistics:

Java A query cache with table timestamps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three requests cost one SQL query, the insert invalidated the cache, and each different parameter is a separate entry. Now imagine a table that changes every second: the cache would be invalidated constantly while still paying for the bookkeeping. That's why the query cache only pays off for read-mostly tables such as countries or categories, and why it's off by default.

Batch inserts with a Session

Inserting 100,000 entities with a naive loop has two problems. Without batching, every persist() becomes its own round trip at flush. And every persisted entity stays in the persistence context until the session ends, so memory grows and every flush has to dirty-check more objects. The fix is a combination of settings and code:

PROPERTIES
hibernate.jdbc.batch_size=50          # group up to 50 statements per JDBC batch
hibernate.order_inserts=true          # sort inserts by table so batches aren't broken up
hibernate.order_updates=true
Java
sessionFactory.inTransaction(session -> {
    for (int i = 0; i < rows.size(); i++) {
        session.persist(new Product(rows.get(i)));
        if ((i + 1) % 50 == 0) {      // same number as batch_size
            session.flush();          // send the batched INSERTs
            session.clear();          // and forget the entities, so memory stays flat
        }
    }
});

Two conditions silently disable insert batching: the entity uses GenerationType.IDENTITY (Hibernate needs each generated key right away, so it inserts one row at a time; use a sequence), or the inserts alternate between tables without order_inserts. The next program runs both versions and counts round trips and the largest persistence context:

Java Flush, clear and JDBC batching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Batching cuts 1,000 round trips to 20, and flush() plus clear() every 50 entities keeps at most 50 objects in memory instead of all 1,000. On a real network the first change is the dramatic speedup; the second is what keeps a 10-million-row import from running out of heap.

StatelessSession for bulk work

For pure bulk jobs (imports, exports, data migrations), a full Session does work you don't need. A StatelessSession has no persistence context: no first-level cache, no dirty checking, no cascades, no lazy loading, and no write-behind. Each call runs its SQL right away, and objects you get back are plain, detached data:

Java
try (StatelessSession session = sessionFactory.openStatelessSession()) {
    Transaction tx = session.beginTransaction();
    for (ProductRow row : csvRows) {
        session.insert(new Product(row.name(), row.price()));     // INSERT now, nothing kept
    }
    Product p = session.get(Product.class, 7L);
    p.setPrice(new BigDecimal("4.99"));                            // NOT saved by itself...
    session.update(p);                                             // ...you must call update()
    tx.commit();
}

Its methods are insert, update, delete, upsert and get, and Hibernate 7 adds insertMultiple() and friends for sending lists of entities in batches. Because there is no context, loading the same row twice returns two different objects, and a forgotten update() simply loses the change. The difference in behavior is easiest to see side by side:

Java Session versus StatelessSession

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The session returns one instance per row and writes the change on its own; the stateless session hands out independent copies and only writes what you explicitly update(). Use StatelessSession for imports and batch jobs that touch many rows once, and the normal Session (or EntityManager) for everything with business logic, relationships and repeated reads.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How are Session and EntityManager related in Hibernate 6 and 7?

    Since Hibernate 5.2, Session extends EntityManager and SessionFactory extends EntityManagerFactory, so you can unwrap and use both on the same persistence context.
  2. 2. Old code calls session.saveOrUpdate(book). What happens after upgrading to Hibernate 7?

    save, update, saveOrUpdate and delete were deprecated in Hibernate 6 and removed in 7. The JPA-style persist, merge and remove replace them.
  3. 3. select a from Author a join fetch a.books with setMaxResults(10). What does Hibernate do by default?

    A SQL limit would cut through an author's books, so Hibernate pages in memory and logs HHH90003004. Page the ids in one query and fetch the collections in a second one, or make the warning an error with fail_on_pagination_over_collection_fetch.
  4. 4. A cacheable query reads the country table. Another transaction inserts a row into country. What happens to the cached result?

    Hibernate tracks an update timestamp per table. Any change to a table makes every cached query result that reads it stale, which is why the query cache suits read-mostly data.
  5. 5. You import 1 million rows with persist() and hibernate.jdbc.batch_size=50, using a sequence for ids, but never call flush() and clear(). What is the main risk?

    Batching still works, but every persisted entity remains managed until the session ends. Flushing and clearing every batch keeps memory flat; a StatelessSession avoids the context entirely.

Summary

  • SessionFactory and Session extend EntityManagerFactory and EntityManager; unwrap() moves between them, and inTransaction/fromTransaction run work in a transaction.
  • Hibernate 7 removed save, update, saveOrUpdate and delete; use persist, merge, remove and find.
  • Configure with hibernate.cfg.xml (native), persistence.xml (JPA) or Spring Boot properties (spring.jpa.properties.hibernate.* for anything not covered by spring.jpa.*).
  • HQL is a superset of JPQL: optional select, limit/offset, new map(...), set operations, CTEs, window functions, and insert statements; selection and mutation queries are separate.
  • Native SQL maps rows to entities, typed scalars or records (tuple transformers, @SqlResultSetMapping). Native updates bypass the persistence context.
  • Never combine setMaxResults with a collection fetch join: page the ids first, then fetch.
  • Statistics (generate_statistics) count statements and cache hits; the query cache is invalidated per table and suits read-mostly data.
  • Bulk inserts need jdbc.batch_size, order_inserts, sequence ids, and flush() plus clear() every batch, or a StatelessSession.

Next: Spring Framework Introduction