Skip to content
javahacks.dev
Hibernate

Hibernate JPA Guide to Mapping Fetching and N Plus 1

Map entities, control fetching and remove the N plus 1 problem in Hibernate 7, with the settings and habits that keep JPA predictable.

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

The Hibernate ORM documentation and the Jakarta Persistence specification are the primary sources for everything below. Hibernate does what you ask, and the trouble is how much of what it does is an implicit default. A @ManyToOne is eager unless you say otherwise, a collection loads one row at a time unless you fetch it, and a session lives as long as your transaction, which may be shorter than you think. This guide fixes those defaults for Hibernate 7 on PostgreSQL 17 and shows where each failure appears. It assumes Spring Boot, as described in Spring Boot from first project to production.

If you want the vocabulary first, Hibernate and JPA, and how they relate separates the specification from the implementation.

Map an entity with explicit intent

src/main/java/dev/javahacks/shop/Order.javajava
@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Version
    private long version;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    protected Order() {}   // required by JPA

    public void addLine(OrderLine line) {
        lines.add(line);
        line.setOrder(this);
    }
}

Three choices here do real work. fetch = LAZY on the @ManyToOne overrides the JPA default, which is EAGER for to-one associations. @Version adds optimistic locking for free. The helper addLine keeps both sides of the bidirectional association in step, which is the part people forget and then wonder why the foreign key is null.

An entity is not a record. Hibernate creates proxy subclasses and sets fields by reflection, so keep entities as ordinary mutable classes with a protected no-argument constructor.

Fetching: ask for what you need

Lazy mapping is only half the answer. The other half is loading what a use case needs, once. There are three tools:

ToolUse it whenCost
JOIN FETCH in JPQLOne association, a known queryCartesian row growth with collections
@EntityGraphA repository method needs a different shapeSame SQL as a fetch join, declared separately
DTO projectionA read-only screen or API responseNo managed entities, no lazy surprises
java
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("select o from Order o join fetch o.customer where o.id = :id")
    Optional<Order> findWithCustomer(@Param("id") Long id);

    @Query("select new dev.javahacks.shop.OrderSummary(o.id, c.name, o.total) " +
           "from Order o join o.customer c where o.status = :status")
    List<OrderSummary> summaries(@Param("status") OrderStatus status);
}

Fetching two collections in one query fails with [MultipleBagFetchException](/library/multiplebagfetchexception-fix-fetch-joins-batching), and the fix is to fetch one collection per query or to batch. Never "fix" it by changing a List to a Set without understanding that the join still multiplies rows.

Find N plus 1 in a test

N plus 1 is one query for a list and one more per row for an association. It hides in development with ten rows and appears in production with ten thousand. Count statements in a test:

java
@DataJpaTest
class OrderQueriesTest {

    @Autowired EntityManager em;

    @Test
    void listingOrdersDoesNotQueryPerRow() {
        Statistics stats = em.getEntityManagerFactory()
                .unwrap(SessionFactory.class).getStatistics();
        stats.setStatisticsEnabled(true);
        stats.clear();

        em.createQuery("select o from Order o", Order.class).getResultList()
          .forEach(o -> o.getCustomer().getName());

        assertThat(stats.getPrepareStatementCount()).isEqualTo(1);
    }
}

With a lazy customer and no fetch join, the count is 1 + number of distinct customers, and the test fails. Add join fetch o.customer and it passes. The full walkthrough, including batch fetching with hibernate.default_batch_fetch_size, is in fixing the Hibernate N plus 1 problem.

Sessions, transactions and the lazy exception

A lazy association loads through the session that loaded its owner. When the session closes, touching the association throws:

Text
org.hibernate.LazyInitializationException: could not initialize proxy [dev.javahacks.shop.Customer#1] - no Session

In Spring, the session lives for the transaction. Set spring.jpa.open-in-view=false and load what the use case needs inside the service method, so the failure shows up in a test. [Fixing LazyInitializationException](/library/lazyinitializationexception-fix-spring-boot-hibernate) lists the options in order of preference.

Saving: persist, merge and the detached trap

An entity is transient (new), managed (in a session), detached (session closed) or removed. save() on a Spring Data repository calls persist for a new entity and merge for an existing id. Passing a detached entity where a new one is expected raises [detached entity passed to persist](/library/detached-entity-passed-persist-fix-spring), and referencing an unsaved entity in an association raises [TransientPropertyValueException](/library/transientpropertyvalueexception-fix-save-spring-data).

Concurrent edits

Two users edit the same order. Without a version column the second save overwrites the first. With @Version, Hibernate adds where version = ? to the update, and the loser gets an optimistic locking failure that you turn into a 409. See [StaleObjectStateException and locking failures](/library/staleobjectstateexception-fix-locking-failures) for retry and message handling.

Schema belongs to migrations

spring.jpa.hibernate.ddl-auto=update is a development convenience that cannot rename a column, drop one safely or reproduce a production schema. Use Flyway or Liquibase for changes and set ddl-auto=validate so Hibernate refuses to start if the mapping and the schema disagree.

Identifiers: the generation strategy changes what Hibernate can batch

The mapping above used GenerationType.IDENTITY, which hands the choice of key to the database column. It is the simplest and has one cost that matters for writes: Hibernate must run the insert immediately to learn the id, so it cannot group inserts into a JDBC batch. A sequence lets Hibernate reserve a block of ids in advance and send many inserts at once:

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

The allocationSize must match the INCREMENT BY of the sequence in your migration, or two application instances will hand out overlapping ids:

SQL
create sequence order_seq start with 1 increment by 50;

PostgreSQL and Oracle have sequences natively. MySQL does not, and on MySQL IDENTITY is the practical choice, with the batching limit that comes with it. If you must generate ids in the application, a UUID version 7 (time-ordered) keeps the index friendly, where a random version 4 scatters inserts across the whole B-tree:

java
@Id
@GeneratedValue
@UuidGenerator(style = UuidGenerator.Style.VERSION_7)
private UUID id;

Check the Hibernate release you use for the generator styles it offers, because this annotation has grown with each major version.

Mapping details that cause quiet bugs

Several defaults are legal and wrong. Enums are mapped by ordinal unless you say otherwise, so inserting a value in the middle of the enum silently reinterprets every stored row:

java
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private OrderStatus status;

Use Instant or OffsetDateTime for points in time, and keep the database column in UTC (timestamp with time zone on PostgreSQL). LocalDateTime has no zone, so it is correct only if every writer agrees on one, and nothing enforces that agreement. Money is BigDecimal with an explicit precision and scale:

java
@Column(nullable = false, precision = 19, scale = 4)
private BigDecimal total;

A value that belongs to an entity and has no identity of its own is an embeddable. Hibernate 6.2 and later accept a record:

java
@Embeddable
public record Address(String street, String city, String postalCode, String country) {}

@Entity
public class Customer {
    @Id @GeneratedValue private Long id;

    @Embedded
    private Address billingAddress;

    @AttributeOverrides({
        @AttributeOverride(name = "street", column = @Column(name = "shipping_street")),
        @AttributeOverride(name = "city", column = @Column(name = "shipping_city")),
        @AttributeOverride(name = "postalCode", column = @Column(name = "shipping_postal_code")),
        @AttributeOverride(name = "country", column = @Column(name = "shipping_country"))
    })
    @Embedded
    private Address shippingAddress;
}

Two embedded values of the same type need column overrides, as above, or the mapping fails at startup with a duplicate column error. For a column that needs custom conversion, such as a type-safe wrapper around a string, write an AttributeConverter with @Converter(autoApply = true) and the mapping stays clean.

Equality and collections: choose a Set, write equals carefully

An entity's equals and hashCode are among the most argued subjects in JPA, and the workable answer is short. The id is null until the entity is persisted, so an implementation based on the id alone breaks a HashSet that held the entity before and after saving. A business key (an email, an ISBN, an order number) works when one exists. When none does, use the id with a stable hash code:

java
@Entity
public class OrderLine {

    @Id @GeneratedValue
    private Long id;

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof OrderLine line)) return false;
        return id != null && id.equals(line.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}

The constant hash code looks wrong and is correct for this purpose: it stays the same before and after the id is assigned, at the cost of every line of one class sharing a bucket. For collections of a few dozen children, that cost is invisible. Do not put a lazy association or a collection into equals, hashCode or toString, because each of those can trigger a load or recurse through a bidirectional mapping.

On the collection type itself: a List without an order column is a "bag" in Hibernate terms, and bags are what make MultipleBagFetchException appear when you fetch two at once. A Set is the honest type for a collection with no meaningful order, and @OrderColumn on a List makes the order persistent, at the price of extra updates when you insert in the middle.

Fetching collections and paging at the same time

A fetch join on a collection multiplies parent rows, which breaks LIMIT. Hibernate warns when you try:

Text
HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory

That line means the database returned every row and Hibernate cut the page in memory, which is a memory problem waiting for a large table. Turn the warning into an error in development so that it cannot reach production:

YAML
spring:
  jpa:
    properties:
      hibernate:
        query:
          fail_on_pagination_over_collection_fetch: true

The correct pattern uses two queries. Page the parent ids first, then fetch the data for just those ids:

java
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("select o.id from Order o where o.status = :status order by o.createdAt desc")
    List<Long> pageIds(@Param("status") OrderStatus status, Pageable page);

    @Query("select distinct o from Order o left join fetch o.lines where o.id in :ids order by o.createdAt desc")
    List<Order> withLines(@Param("ids") List<Long> ids);
}
java
@Transactional(readOnly = true)
public List<Order> latest(OrderStatus status, int size) {
    List<Long> ids = orders.pageIds(status, PageRequest.of(0, size));
    return ids.isEmpty() ? List.of() : orders.withLines(ids);
}

Each query is simple and indexed, and the page size is enforced by the database. When the screen needs two collections, run a third query for the second one in the same style, and let the persistence context stitch the results together, since the entities are the same instances in one session.

Batch fetching as a safety net

Even careful code leaves some lazy loads. hibernate.default_batch_fetch_size turns the remaining N plus 1 into N divided by the batch size:

YAML
spring:
  jpa:
    properties:
      hibernate:
        default_batch_fetch_size: 32

With a value of 32, loading the lines of 100 orders issues four queries with an in list instead of 100. It is a safety net rather than a replacement for fetch joins, because it still issues more statements than one join would. Set it globally, and use @BatchSize on a single association when only one needs it.

Writing efficiently

Reads get the attention, and writes cause a surprising share of the load. Two settings and one habit cover most of it:

YAML
spring:
  jpa:
    properties:
      hibernate:
        jdbc:
          batch_size: 50
        order_inserts: true
        order_updates: true

batch_size groups inserts and updates into JDBC batches, and the order_ flags sort statements by entity so that batches can form. The habit is to flush and clear in a loop when you process many entities, since the persistence context keeps every entity you touch:

java
@Transactional
public void importOrders(Iterator<NewOrder> source) {
    int count = 0;
    while (source.hasNext()) {
        em.persist(Order.from(source.next()));
        if (++count % 50 == 0) {
            em.flush();
            em.clear();
        }
    }
}

Without clear(), an import of a million rows grows the session until the heap runs out, and dirty checking slows as it grows. For an update that touches many rows by a rule, such as closing every order older than a year, skip entities and use one statement:

java
@Modifying
@Query("update Order o set o.status = 'CLOSED' where o.status = 'SHIPPED' and o.createdAt < :before")
int closeOlderThan(@Param("before") Instant before);

A bulk update bypasses the persistence context, so entities already loaded in the session do not see the change, and the @Version column is not bumped unless you do it in the query. Run it at the start of a transaction, or clear the context afterwards.

Locking: optimistic by default, pessimistic where it pays

The @Version column from the first example covers the common case of two people editing one record. When the conflict is frequent and the work is cheap to repeat, retry:

java
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
@Transactional
public void rename(long id, String name) {
    Customer c = customers.findById(id).orElseThrow();
    c.rename(name);
}

Put the retry outside the transaction, so that each attempt gets a fresh one, which means the annotated method must be called through the proxy and from a bean that is not itself in the same transaction. When correctness depends on one writer at a time, such as allocating the last unit of stock, lock the row:

java
public interface StockRepository extends JpaRepository<Stock, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "2000"))
    @Query("select s from Stock s where s.sku = :sku")
    Optional<Stock> lockBySku(@Param("sku") String sku);
}

The query becomes select ... for update, and the timeout turns an endless wait into an exception you can report. For a work queue where many workers each want one free row, the hint jakarta.persistence.lock.timeout set to -2 requests SKIP LOCKED on databases that support it, so workers pass over rows another transaction holds. Check your database and Hibernate version for the exact behavior before relying on it.

Caching: what Hibernate holds for you

The first-level cache is the persistence context itself: within one session, loading the same id twice returns the same instance and runs one query. It is why findById in a loop is cheaper than it looks and why a long session slows down. The second-level cache is optional and lives across sessions. It pays for reference data that is read often and changed rarely, such as countries or tax tables:

java
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country {
    @Id private String code;
    private String name;
}
YAML
spring:
  jpa:
    properties:
      hibernate:
        cache:
          use_second_level_cache: true
          region.factory_class: jcache
      jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE

You also need a JCache provider such as Ehcache or Caffeine on the classpath. Be cautious with the query cache, which stores result ids and is invalidated on any write to the tables involved, so it helps only on near-static data. A cache is a consistency risk across several application instances unless it is a distributed one, so measure the gain before you accept the risk. If the same data can be served from the application's own cache with an explicit expiry, that is often easier to reason about.

Auditing and soft deletes

Two requirements appear in nearly every business application, and both have small, standard answers. Spring Data auditing fills in who and when:

java
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {

    @CreatedDate @Column(updatable = false)
    private Instant createdAt;

    @LastModifiedDate
    private Instant updatedAt;

    @CreatedBy @Column(updatable = false)
    private String createdBy;
}

Enable it with @EnableJpaAuditing and provide an AuditorAware<String> bean that returns the current user. Soft deletion is built into recent Hibernate releases:

java
@Entity
@SoftDelete
public class Document {
    @Id @GeneratedValue private Long id;
    private String title;
}

With @SoftDelete, delete marks the row and every query excludes it, without a hand-written where deleted = false on each repository method. Think about unique constraints before you adopt it, since a deleted row still holds its unique value, and about whether regulations require real deletion, in which case soft delete is the wrong tool.

Tests that protect the mapping

A JPA mapping fails at runtime in ways a compiler cannot see, so a few tests are worth more than usual. Run them against the real database engine, which Testcontainers makes easy:

java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class MappingTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired TestEntityManager em;

    @Test
    void orderRoundTripsWithLinesAndVersion() {
        Customer customer = em.persist(new Customer("Ada"));
        Order order = new Order(customer);
        order.addLine(new OrderLine("sku-1", 2));
        em.persistAndFlush(order);
        em.clear();

        Order loaded = em.find(Order.class, order.getId());

        assertEquals(1, loaded.getLines().size());
        assertEquals(0L, loaded.getVersion());
    }
}

With ddl-auto=validate and your migrations applied to the container, this test fails at startup if a column is missing or mistyped, which catches most mapping drift before a deployment does. Combine it with the statement-counting test from the N plus 1 section for every query that serves a list.

Read the SQL while you develop

Hibernate's job is to write SQL for you, so read it. In development, print the statements with their parameter values, formatted, and keep it off in production:

YAML
spring:
  jpa:
    show-sql: false
logging:
  level:
    org.hibernate.SQL: DEBUG
    org.hibernate.orm.jdbc.bind: TRACE

The org.hibernate.SQL logger prints each statement through your normal logging, and the bind logger prints the parameters. Scan the output for three signs of trouble: the same statement repeated many times with different ids (N plus 1), a select on a table you did not expect to touch (an eager association), and an update you did not ask for (dirty checking flushing a change you made by accident, such as a setter that normalizes a value on read).

Exceptions and what they usually mean

ExceptionUsual causeFirst move
LazyInitializationExceptionAssociation read after the session closedLoad it in the use case, or return a DTO
MultipleBagFetchExceptionTwo List collections in one fetch joinFetch one per query
StaleObjectStateExceptionOptimistic lock lostReload and retry, or return 409
DataIntegrityViolationExceptionA constraint rejected the writeRead the nested SQL state and constraint name
TransientObjectExceptionAssociation points at an unsaved entitySave the child first, or use cascade
NonUniqueResultExceptionA query expected one row and found severalFix the query or the data, never LIMIT 1 to silence it
QueryException: could not resolve propertyTypo in JPQLCompile-time checking with the JPA metamodel

Treat the table as a map, and follow it with the post that covers each case in depth. Most Hibernate trouble is one of the first three, and the first three are the three decisions listed at the top of this guide.

A short review checklist for a JPA pull request

When a pull request touches an entity or a repository, five questions find most of the trouble before it ships. Does every association say how it is fetched, and is each to-one association lazy? Does each list endpoint have a test that counts statements, so a new association cannot quietly add one query per row? Is the transaction boundary on the service method that runs the use case, with nothing slow, such as a remote call, inside it? Did the schema change arrive as a migration, and does the mapping still validate against it? And if two users can edit the record, is there a version column and a response for the conflict?

The answers take a minute to read in a diff, and a reviewer who asks them every time teaches the team the three decisions at the top of this guide without a single lecture. Keep the list in the repository with the pull request template, and add a line to it each time a production issue traces back to something it did not ask.

What Hibernate does not suit

Hibernate is a good fit for a domain model that is read and written in units of aggregates. It is a poor fit for reporting queries over millions of rows, bulk updates and anything where you think in sets: write those in SQL through JdbcClient or a native query, and keep the object model for the writes. If the database is the center of your design, JDBC is the honest tool, and nothing stops you using both in one service.

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.