▚ The Software Engineer's Field Manual
Chapter E5 · Primer + senior drill

Hibernate & JPA — Primer + 150-Question Drill

"An ORM does not hide the database. It hides the moment your code talks to it — and every production Hibernate incident is a story about that moment arriving somewhere you did not expect."

150 questions · answers collapsed For: ~9-year engineers prepping the senior round Heavy on: persistence context · N+1 · batching · locking · migrations

01 · Why this primer existsYou Annotate Entities Daily — Nobody Ever Taught You What Happens Between persist() and COMMIT

JPA hides the database behind objects. Almost every performance problem in a Boot service comes from not knowing which SQL that hiding produces, and when.

Nine years of Spring Boot means you have written @Entity hundreds of times, typed repository.save(order) without thinking, and fixed at least one LazyInitializationException by adding @Transactional somewhere until the stack trace went away.

The senior interview finds the gap in that experience fast: when exactly does Hibernate send the INSERT? Why did one endpoint issue 1,200 queries? Why does GenerationType.IDENTITY quietly make your bulk import ten times slower? What does save() do when the id is already set? These are not trick questions.

They probe whether you understand the layer your code leans on for every read and write — and they are answerable from a small set of ideas this primer teaches in plain words: the persistence context, the flush, the owning side of a relationship, the fetch plan, and the JDBC batch.

Interviewers probe Hibernate from three directions. First, mechanism: "walk me through what happens, line by line, when this method runs" — they want to hear about the identity map, the dirty check, and the moment of flush.

Second, incidents: "an endpoint is slow only in production", "an OptimisticLockException storm at month-end", "a batch job's heap grows until it dies" — they want a diagnosis in order, not a guess.

Third, design: "model orders with line items and audit history", "design id generation for a sharded system", "when would you not use an ORM at all" — they want requirements, trade-offs, and a clear statement of what you would refuse to do.

All three directions come back to the same handful of internals, which is why the primer comes first.

How to use the drill: read each question, say the answer aloud in full sentences as if the interviewer were across the table, and only then open Reveal answer.

Scenario questions have answers in diagnosis order — symptom, evidence to collect, likely causes ranked, fix, prevention — because that ordering is itself what the interviewer grades.

Design questions state requirements and assumptions before the design, then the trade-offs, then what you would not do. Every answer ends with a Land it sentence: the one-line decision you want the interviewer to remember.

Map of the page. The primer is sections 02–06: the persistence context and entity lifecycle (02), mapping, ids, relationships and locking (03), fetching and the N+1 problem (04), batching, caches and session types (05), and migrations, schema and Spring Data JPA specifics (06).

The drill is sections 07–10: 150 questions in four blocks that follow the primer's order and end with production scenarios and design.

Two neighbouring appendices carry depth this page only points at: the Database Primer (E8) for isolation levels, MVCC and indexes, and Spring Boot (E4) for how @Transactional proxies actually work.

Version claims are as of August 2026: Spring Boot 3.5 ships Hibernate 6.6, Spring Boot 4.x (released November 2025) ships Hibernate 7.x on Jakarta Persistence 3.2, and every code block on this page runs on Java 21 with either line.

02 · The primerWhat an ORM Really Does: The Persistence Context

The persistence context is a write-back cache. Your changes go into memory, and Hibernate works out the SQL and sends it later — which is why the statement you expected often is not the statement the database receives.

Start with a number.

A typical Spring Boot service method that loads a customer, changes one field, and returns takes about 2 milliseconds on a warm connection pool — one SELECT and one UPDATE. Now put that same method behind an endpoint that calls it 400 times per request, and the request takes 800 milliseconds and issues 800 statements.

Nothing in the Java code looks wrong. Understanding why both numbers happen, and where between the lines of Java the SQL is actually sent, is the whole first chapter.

You already know the shape of the idea from something else: a write-back cache.

A CPU does not write every changed byte straight to main memory; it changes the byte in its cache, marks the cache line dirty, and writes it back later, in a batch, at a moment the hardware chooses. Hibernate treats your entities exactly the same way.

It keeps your loaded objects in a private in-memory map, lets you change them freely, and writes the changes to the database later, at a moment it chooses — the flush. Almost every surprising Hibernate behaviour is a consequence of that one deferral.

The persistence context, in plain words

The persistence context is the map Hibernate keeps for one unit of work. Every entity Hibernate has loaded or saved during that unit of work lives in it, keyed by two things: the entity class and the primary key. JPA calls the object that owns this map the EntityManager; Hibernate's older name for the same thing is the Session. The two names describe one object, and in Spring you meet it through @PersistenceContext injection or, far more often, hidden inside a Spring Data repository.

Because the map is keyed by class and id, it behaves as an identity map: within one persistence context, asking for customer 42 twice gives you the same Java object both times, and the second ask does not touch the database at all.

This is why the persistence context is also called the first-level cache. It is not a performance cache you configure; it is a correctness structure that happens to save queries.

It guarantees that two parts of your transaction can never disagree about what customer 42 looks like, because there is only one customer 42 in memory.

Every entity object is, at any moment, in one of four states relative to a persistence context:

The transitions between these states are the vocabulary of the whole chapter. persist() moves transient to managed. Loading with find() or a query hands you objects that are already managed. Closing the context moves managed to detached.

merge() takes a detached (or transient) object, finds or loads the managed copy with the same id, copies your object's field values onto that managed copy, and returns the managed copy — your original object stays detached, which is the single most common source of "I set the field but it did not save" bugs.

persistence context (EntityManager / Session) — the identity map Transient new Customer() Managed watched, flushed on commit Removed DELETE at flush Detached persist() remove() close() / clear() / detach() merge() → copy find() / query returns managed outside the context nobody is watching
Fig. E5.1 — The four entity states. Only objects inside the dashed box are watched. The highlighted merge() arrow is the one that surprises people: it copies your detached object's fields onto a managed copy and returns that copy; the object you passed in stays outside the box.

Flush and dirty checking: when the SQL actually goes out

A flush is the moment Hibernate turns the contents of the persistence context into SQL. At flush time, for every managed entity, Hibernate performs a dirty check: when it loaded the entity it quietly kept a copy of every field's value — the snapshot — and now it compares the current field values against that snapshot. Any entity whose values differ is dirty, and Hibernate generates an UPDATE for it. You never call update(); changing a managed object's field is the update. New entities become INSERTs, removed ones become DELETEs, and Hibernate orders the statements so that foreign keys are satisfied: inserts first, then updates, then collection changes, then deletes.

Three things trigger a flush under the default FlushModeType.AUTO. First, the transaction commit — this is the one everyone knows.

Second, a JPQL or criteria query whose tables overlap with dirty entities: Hibernate flushes first so the query does not return stale results from its own transaction.

Third, a native SQL query: Hibernate cannot parse arbitrary SQL to know which tables it touches, so it flushes everything before running it.

Calling flush() yourself is the fourth trigger, and it is rarer than people think — it is the right tool in exactly two situations, forcing an INSERT to happen before a native query that needs to see the row, and clearing the context during a batch job (the next chapter).

The snapshot has a memory cost worth naming: every managed entity exists twice, once as your object and once as the snapshot array. Load 500,000 entities inside one transaction and you hold a million objects. That is the first mechanism behind "the batch job's memory blows up", and read-only transactions (chapter 05) are the standard relief because they skip the snapshot.

How a Session maps to a transaction in Spring

In a Spring Boot application you never open an EntityManager yourself.

When a call enters a method annotated @Transactional, the transaction interceptor asks the JpaTransactionManager to begin a transaction; that creates a fresh persistence context, binds it to the current thread, and borrows a JDBC connection from HikariCP. Every repository call inside that method, however deep the call stack, finds the same thread-bound context and therefore shares the same identity map.

When the outermost @Transactional method returns, Spring commits: Hibernate flushes, the JDBC commit runs, the persistence context closes, and every entity you loaded becomes detached.

The appendix on Spring Boot (E4) covers the proxy mechanics — why a self-call skips the interceptor, why private methods are never transactional — and those rules matter here because "no transaction" means "no persistence context", which means no dirty checking and no lazy loading.

One Spring Boot default changes this picture and deserves its own warning: open-session-in-view (spring.jpa.open-in-view, still true by default in Boot 3.5 and 4.x, with a startup warning if you have not set it explicitly).

With it on, a web request gets a persistence context for the whole request, opened by a filter before your controller runs and closed after the response is written.

Transactions come and go inside it, but the context — and its ability to lazy-load — survives across them. It hides LazyInitializationException in development and hides N+1 queries in production, and chapter 04 explains why the professional default is to turn it off.

A save and a find, line by line

The best way to make all of this concrete is to watch the SQL. The entity below is deliberately minimal; the walkthrough service after it does one save and one find, and the comments say what Hibernate sends at each line when the log shows SQL. Both files compile as written against Spring Boot 3.5 or 4.x.

Step-by-step: what Customer.java does, in plain English
  1. @Entity tells Hibernate this class maps to a table; @Table(name = "customer") pins the table name so a naming strategy change can never rename it underneath you.
  2. @Id with GenerationType.SEQUENCE says the database sequence customer_seq supplies ids, fifty at a time (allocationSize = 50), so Hibernate can assign ids in memory without a round trip per row and can batch the INSERTs.
  3. @Version adds an optimistic-lock column: every UPDATE carries WHERE version = ? and bumps it, so two concurrent edits of the same row cannot silently overwrite each other.
  4. The email column is marked nullable = false, unique = true so the schema — generated for tests, or validated in production — carries the constraint, not just the Java code.
  5. The protected no-argument constructor exists only because Hibernate needs one to build objects by reflection; the public constructor is the one your code uses.
  6. equals and hashCode use only the id, and treat two objects with null ids as unequal, so a transient entity keeps a stable hash before and after it gets an id — which is what makes it safe to put entities in a HashSet.
Customer.javaruns offline
package com.shopstream.orders;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import jakarta.persistence.Version;

@Entity
@Table(name = "customer")
public class Customer {

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

    @Version
    private long version;

    @Column(nullable = false, unique = true, length = 254)
    private String email;

    @Column(nullable = false, length = 120)
    private String displayName;

    protected Customer() {
        // Hibernate builds instances by reflection; nobody else should call this.
    }

    public Customer(String email, String displayName) {
        this.email = email;
        this.displayName = displayName;
    }

    public Long getId() { return id; }
    public long getVersion() { return version; }
    public String getEmail() { return email; }
    public String getDisplayName() { return displayName; }
    public void rename(String newDisplayName) { this.displayName = newDisplayName; }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Customer that)) return false;
        // Two unsaved customers are never equal; a saved one is equal only to itself by id.
        return id != null && id.equals(that.id);
    }

    @Override
    public int hashCode() {
        // Constant hash keeps a transient entity findable in a HashSet after it gains an id.
        return Customer.class.hashCode();
    }
}
Step-by-step: what CustomerWalkthrough.java does, in plain English
  1. The class is a Spring @Service; the injected EntityManager is a thread-aware proxy that always resolves to the persistence context of the current transaction.
  2. @Transactional on run() means one persistence context and one JDBC connection live from the first line to the last.
  3. persist(alice) makes the object managed. Because ids come from a sequence, Hibernate calls next value for customer_seq once (and remembers a block of 50) — but sends no INSERT yet.
  4. find(Customer.class, alice.getId()) hits the identity map and returns the same object without any SQL; the == check proves it.
  5. rename(...) changes a field on a managed object; nothing is sent, the object is merely now different from its snapshot.
  6. The JPQL count query touches the customer table, which has pending changes, so Hibernate flushes first: the INSERT goes out now, then the SELECT COUNT runs and correctly sees one row.
  7. clear() empties the persistence context; alice is now detached, and the second find must go to the database: a real SELECT, returning a different Java object.
  8. On return, Spring commits. Nothing is dirty by then (the rename was already flushed with the INSERT, since flush writes the current field values), so commit sends only COMMIT.
CustomerWalkthrough.javaruns offline
package com.shopstream.orders;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerWalkthrough {

    private static final Logger log = LoggerFactory.getLogger(CustomerWalkthrough.class);

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public void run() {
        Customer alice = new Customer("alice@example.com", "Alice");   // transient
        log.info("1. new Customer: id={}", alice.getId());               // id=null

        em.persist(alice);                                               // managed; SQL: select next value for customer_seq
        log.info("2. after persist: id={} (no INSERT sent yet)", alice.getId());

        Customer again = em.find(Customer.class, alice.getId());         // identity map hit, no SQL
        log.info("3. find by id returns the same object? {}", again == alice);

        alice.rename("Alice Liddell");                                   // dirty, still no SQL
        log.info("4. renamed in memory; nothing sent");

        long count = em.createQuery("select count(c) from Customer c", Long.class)
                       .getSingleResult();                               // AUTO flush: INSERT first, then the SELECT
        log.info("5. query forced a flush; count={}", count);

        em.clear();                                                      // everything detached
        Customer reloaded = em.find(Customer.class, alice.getId());      // real SELECT this time
        log.info("6. after clear, find returns the same object? {} name={}",
                 reloaded == alice, reloaded.getDisplayName());
        // method returns -> Spring commits: flush (nothing dirty) + COMMIT
    }
}
walkthrough.log — with org.hibernate.SQL at DEBUG
1. new Customer: id=null
    select next value for customer_seq
2. after persist: id=1 (no INSERT sent yet)
3. find by id returns the same object? true
4. renamed in memory; nothing sent
    insert into customer (display_name,email,version,id) values (?,?,?,?)
    select count(c1_0.id) from customer c1_0
5. query forced a flush; count=1
    select c1_0.id,c1_0.display_name,c1_0.email,c1_0.version from customer c1_0 where c1_0.id=?
6. after clear, find returns the same object? false name=Alice Liddell

Read the output top to bottom, because every line is a lesson. Line 2 shows the id is assigned by a sequence call, not by an INSERT — that separation is what makes batching possible in chapter 05, and it is exactly what GenerationType.IDENTITY takes away, because an identity column only yields its value after the INSERT runs. Line 3's true is the identity map: same id, same object, no query. Between lines 4 and 5 the INSERT finally appears, and notice that it carries Alice Liddell, the renamed value — the flush writes whatever the fields hold at flush time, so the rename never needed its own UPDATE. Line 6's false is detachment: after clear(), the persistence context is empty, so the same id yields a fresh object from a fresh SELECT. Had you renamed alice after the clear, nothing would ever have been saved, and that is the whole detached-entity trap in one line.

🧠 Brain power

Before reading on: a colleague changes the id strategy in Customer.java to GenerationType.IDENTITY and reruns the walkthrough. Which log lines change, and what does step 2 now cost per row in a loop of 10,000 persists?

Reveal the answer

With IDENTITY, the INSERT moves up to line 2: Hibernate must execute it immediately inside persist(), because the only way to learn an auto-increment id is to run the INSERT and read the generated key back.

The sequence call disappears, and the count query at line 5 no longer needs to flush an insert — but the rename still goes out as a separate UPDATE at commit, because the row already existed when it was renamed.

In a loop of 10,000 persists, IDENTITY means 10,000 individual INSERT round trips, each waiting on the network, because Hibernate cannot batch statements whose results it needs one by one.

With SEQUENCE and allocationSize = 50, the same loop costs 200 sequence calls and, with JDBC batching on, 200 batched INSERT round trips. That is the ten-times difference chapter 05 measures.

Quick reference — The persistence context

persistence context
A write-back cache plus an identity map, scoped to one transaction. Also called the first-level cache.
The four states
Transient (new, unknown) → Managed (tracked, changes will be written) → Detached (was managed, context closed) → Removed (queued for delete).
dirty checking
At flush, Hibernate compares each managed entity against the snapshot it took at load, and writes UPDATEs for what changed. You never call update().
flush
When the queued SQL is actually sent: before a query that would be affected, and at commit. Not when you call the setter.
open-session-in-view
Keeps the context open for the whole HTTP request, so lazy loads in the view layer silently work — and silently issue queries. Turn it off.

03 · The primerMapping: Ids, Relationships, Ownership & Locking

How an object graph becomes tables: who owns a relationship, which id strategy lets Hibernate batch, and what cascade actually repeats.

A concrete failure first. A team adds @ManyToMany List<Tag> tags to a Product entity.

Removing one tag from a product with 30 tags issues 31 statements: one DELETE that wipes every row of the join table for that product, then 29 INSERTs to put the survivors back.

Under load, two requests editing the same product's tags deadlock on the join table, and the on-call engineer sees "deadlocks after adding a @ManyToMany" with no idea why a one-line annotation caused it.

The reason is the mapping: a List with no order column is a bag, a collection Hibernate cannot address element by element, so it rewrites the whole thing. Change List to Set and the same removal is one DELETE of one row.

Mapping annotations are not documentation; they are instructions that decide which SQL is generated, and this chapter is about reading them that way.

The bridge from what you know: a mapping is a compiler target. Just as the JIT turns the same Java loop into different machine code depending on the types involved, Hibernate turns the same save() call into different SQL depending on the id strategy, the owning side, the collection type, and the cascade settings. Reading a mapping means predicting the SQL.

Ids: IDENTITY versus SEQUENCE, and why it decides your batch speed

An @Id needs a value before Hibernate can put the entity in the identity map, because the map is keyed by id. Where that value comes from is the generation strategy, and the choice has consequences far beyond style.

One Hibernate 6 change still catches migrating teams as of 2026: the old shared hibernate_sequence is gone. Each entity now defaults to its own sequence named <table>_seq with an increment of 50, so a schema written for Hibernate 5 fails validation until you either create those sequences in a migration or map the old name explicitly with @SequenceGenerator.

Relationships and the owning side

Every relationship between two tables is, physically, one foreign key column living in one table.

JPA lets you see the relationship from both Java sides — an Order has a list of lines, a line has its order — but only one side can be responsible for writing that column.

That side is the owning side, and it is always the side that holds the foreign key: for a one-to-many, the many side. The other side declares mappedBy = "order", which means "I am a read-only mirror; the field named order over there owns this".

The rule that follows is the one every Hibernate developer breaks once: Hibernate only looks at the owning side when flushing. If you add a line to order.getLines() but never set line.setOrder(order), the foreign key stays null and the line is orphaned in the database, even though your in-memory graph looks perfect. The fix is a pair of helper methods on the parent that maintain both sides at once (addLine and removeLine in the entity below), so no caller can get it wrong.

Java objects Order @OneToMany(mappedBy = "order") lines inverse side — mirror only OrderLine @ManyToOne @JoinColumn("order_id") order owning side — writes the column holds a List points at parent tables orders id · customer_id · status · version order_line id · order_id (FK) · sku · qty · price FK order_id flush writes order_id from here List ignored at flush
Fig. E5.2 — One foreign key, two Java views. Only the owning side (the @ManyToOne holding the column) is consulted when Hibernate writes order_id. Adding to the parent's List without setting the child's reference leaves the column null.

Cascade, orphanRemoval, embeddables, inheritance and enums

Cascade tells Hibernate to repeat an operation on related entities: cascade = CascadeType.ALL on Order.lines means persisting an order persists its lines and removing an order removes its lines. Cascade belongs on relationships where the child has no life of its own — an order line without an order is meaningless. It does not belong on shared references: CascadeType.REMOVE on OrderLine.product would delete the product catalogue entry when a line is deleted, and on a @ManyToMany it deletes the other side's rows that other parents still point at. orphanRemoval = true is a stronger promise: a child that is removed from the parent's collection is deleted, not merely unlinked. It is the right choice for true composition (lines of an order) and the wrong choice when the child can be moved to another parent.

An @Embeddable is a value object whose fields live in the parent's table as extra columns — a Money with amount and currency, an Address. It has no id and no table; equality is by value. Since Jakarta Persistence 3.2 a Java record can be an embeddable, which is the natural fit because records are immutable and value-equal by construction. Use embeddables wherever a group of columns means one thing; they cost nothing at query time and make the domain model honest.

Inheritance has three strategies, and the choice is a query-versus-schema trade.

SINGLE_TABLE (the default) puts every subclass in one table with a discriminator column saying which subclass each row is: fastest queries, no joins, but every subclass-specific column must be nullable, so the database cannot enforce "a card payment always has a last-four".

JOINED gives each subclass its own table joined to the parent by primary key: proper constraints, at the cost of one join per level in every polymorphic query.

TABLE_PER_CLASS duplicates the parent's columns into every subclass table and answers polymorphic queries with a UNION — and it cannot use IDENTITY ids, because ids must be unique across tables.

@MappedSuperclass is not inheritance mapping at all: it shares fields (audit columns, ids) with subclasses without any polymorphic queries, and it is what you want for a base class like AuditedEntity.

Enums have one rule: @Enumerated(EnumType.STRING), never ORDINAL. Ordinal stores the position in the Java declaration, so inserting a constant in the middle of the enum silently remaps every stored row. Hibernate 6.2 and later can also map an enum to a native Postgres enum type or a MySQL ENUM column through @JdbcType; the storage is compact, but adding a value then requires an ALTER TYPE migration, so most teams keep a varchar with a check constraint.

Optimistic locking with @Version, and pessimistic locks

Two users open the same order at 10:00. One changes the shipping address and saves at 10:01; the other changes the quantity and saves at 10:02.

Without protection, the second save writes the whole row and the address change is gone — the lost update, explained in depth in E8's isolation chapter.

Optimistic locking prevents it without holding any database lock: a @Version column (an integer or a timestamp) is read with the entity and every UPDATE becomes UPDATE orders SET ..., version = 6 WHERE id = ? AND version = 5.

If the row's version has already moved to 6, the UPDATE matches zero rows, and Hibernate throws OptimisticLockException (Spring wraps it as ObjectOptimisticLockingFailureException). The loser retries with fresh data, or shows the user a conflict.

The cost is zero contention and one retry per real conflict, which is why it is the right default for web workloads where conflicts are rare.

Pessimistic locking takes a real database row lock at read time: em.find(Order.class, id, LockModeType.PESSIMISTIC_WRITE) becomes SELECT ... FOR UPDATE, and any other transaction wanting the same row waits until you commit.

It is right when conflicts are the normal case — a stock counter every checkout decrements, a job-queue row many workers race for.

Two hints matter in production: jakarta.persistence.lock.timeout set to 0 turns the wait into an immediate failure (NOWAIT), and Hibernate's value -2 (the constant LockOptions.SKIP_LOCKED; Hibernate 7 also offers Timeouts.SKIP_LOCKED) makes the query skip rows other workers hold, which is the correct pattern for a database-backed queue.

Pessimistic locks are held to the end of the transaction, so a long transaction with a pessimistic lock is a queue for everyone else — keep those transactions short.

The order model, complete

Here are the two entities the rest of the page builds on. They show sequence ids, a versioned aggregate root, an embeddable record, an owning-side @ManyToOne, a mappedBy collection with cascade and orphan removal, helper methods that keep both sides in sync, and an enum stored as a string.

Step-by-step: what Order.java does, in plain English
  1. The table is named orders rather than order because order is an SQL reserved word; an explicit index on customer_id and status is declared where the schema tooling can see it.
  2. The id comes from orders_seq in blocks of 50, exactly like Customer, so a checkout that creates one order and five lines can flush all six INSERTs in two batches.
  3. @Version makes every update conditional on the version read earlier — the optimistic lock.
  4. customer is a @ManyToOne declared LAZY explicitly, because the JPA default for to-one relationships is EAGER, which would join the customer into every order load whether you need it or not.
  5. lines is the inverse side (mappedBy = "order"): a List with an @OrderColumn so it is an indexed list, not a bag, and Hibernate can update single elements. cascade = ALL plus orphanRemoval = true says lines live and die with their order.
  6. status is an enum stored as text, so a reordering of the Java constants can never corrupt existing rows.
  7. total is a Money record embedded as two columns, total_amount and total_currency.
  8. addLine and removeLine set both sides of the relationship in one place, so callers cannot create an orphaned line by forgetting setOrder.
  9. equals/hashCode follow the same id-based rule as Customer.
Order.javaruns offline
package com.shopstream.orders;

import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import jakarta.persistence.Version;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Entity
@Table(name = "orders", indexes = @Index(name = "ix_orders_customer_status", columnList = "customer_id, status"))
public class Order {

    public enum Status { NEW, PAID, SHIPPED, CANCELLED }

    /** A value object stored as two columns of the owning table. Records are embeddable since Jakarta Persistence 3.2. */
    @Embeddable
    public record Money(@Column(nullable = false, precision = 19, scale = 4) BigDecimal amount,
                        @Column(nullable = false, length = 3) String currency) {
        public Money add(Money other) {
            if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
            return new Money(amount.add(other.amount), currency);
        }
    }

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

    @Version
    private long version;

    // The JPA default for to-one is EAGER; say LAZY explicitly so loading an order never drags the customer along.
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id", nullable = false)
    private Customer customer;

    // Inverse side: OrderLine.order owns the foreign key. @OrderColumn makes this an indexed list, not a bag.
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderColumn(name = "line_no")
    private List<OrderLine> lines = new ArrayList<>();

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 16)
    private Status status = Status.NEW;

    @Embedded
    @AttributeOverrides({
        @AttributeOverride(name = "amount", column = @Column(name = "total_amount")),
        @AttributeOverride(name = "currency", column = @Column(name = "total_currency"))
    })
    private Money total;

    @Column(nullable = false, updatable = false)
    private Instant createdAt = Instant.now();

    protected Order() { }

    public Order(Customer customer, String currency) {
        this.customer = customer;
        this.total = new Money(BigDecimal.ZERO, currency);
    }

    /** Keeps both sides of the relationship consistent; the only sanctioned way to add a line. */
    public OrderLine addLine(Product product, int quantity) {
        OrderLine line = new OrderLine(this, product, quantity);
        lines.add(line);
        total = total.add(line.lineTotal());
        return line;
    }

    public void removeLine(OrderLine line) {
        if (lines.remove(line)) {
            line.detachFromOrder();          // orphanRemoval turns this into a DELETE at flush
            total = new Money(total.amount().subtract(line.lineTotal().amount()), total.currency());
        }
    }

    public void markPaid() {
        if (status != Status.NEW) throw new IllegalStateException("only NEW orders can be paid");
        status = Status.PAID;
    }

    public Long getId() { return id; }
    public long getVersion() { return version; }
    public Customer getCustomer() { return customer; }
    public List<OrderLine> getLines() { return Collections.unmodifiableList(lines); }
    public Status getStatus() { return status; }
    public Money getTotal() { return total; }
    public Instant getCreatedAt() { return createdAt; }

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

    @Override
    public int hashCode() { return Order.class.hashCode(); }
}
Step-by-step: what OrderLine.java and Product.java do, in plain English
  1. OrderLine.order is the owning side of the order–line relationship: the @JoinColumn here is the physical order_id column, and it is declared not-null so an orphan can never be inserted.
  2. product is a lazy @ManyToOne with no cascade: deleting a line must never delete a catalogue product.
  3. unitPrice is copied from the product at the time of the order, so later price changes do not rewrite history — a deliberate denormalisation.
  4. detachFromOrder() is package-private so only Order.removeLine can null the parent reference, which is what orphan removal keys on.
  5. Product is a plain catalogue entity with a unique SKU and its own sequence; it has no reference back to lines, because "all lines that ever sold this product" is a query, not a navigable collection.
OrderLine.java · Product.javaruns offline
// ---- OrderLine.java ----
package com.shopstream.orders;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import java.math.BigDecimal;

@Entity
@Table(name = "order_line")
public class OrderLine {

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

    // Owning side: this column IS the relationship.
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "order_id", nullable = false)
    private Order order;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "product_id", nullable = false)
    private Product product;

    @Column(nullable = false)
    private int quantity;

    // Snapshot of the price at order time; catalogue changes must not rewrite old orders.
    @Column(nullable = false, precision = 19, scale = 4)
    private BigDecimal unitPrice;

    protected OrderLine() { }

    OrderLine(Order order, Product product, int quantity) {
        this.order = order;
        this.product = product;
        this.quantity = quantity;
        this.unitPrice = product.getPrice();
    }

    void detachFromOrder() { this.order = null; }

    public Order.Money lineTotal() {
        return new Order.Money(unitPrice.multiply(BigDecimal.valueOf(quantity)), order.getTotal().currency());
    }

    public Long getId() { return id; }
    public Order getOrder() { return order; }
    public Product getProduct() { return product; }
    public int getQuantity() { return quantity; }
    public BigDecimal getUnitPrice() { return unitPrice; }

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

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

// ---- Product.java ----
package com.shopstream.orders;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import java.math.BigDecimal;

@Entity
@Table(name = "product")
public class Product {

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

    @Column(nullable = false, unique = true, length = 32)
    private String sku;

    @Column(nullable = false, length = 200)
    private String name;

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

    protected Product() { }

    public Product(String sku, String name, BigDecimal price) {
        this.sku = sku;
        this.name = name;
        this.price = price;
    }

    public Long getId() { return id; }
    public String getSku() { return sku; }
    public String getName() { return name; }
    public BigDecimal getPrice() { return price; }

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

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

Read the mapping as SQL. Creating an order with three lines and calling save produces: one sequence call (if the block of 50 is exhausted), one INSERT into orders, three INSERTs into order_line each carrying order_id and line_no — and with batching enabled in chapter 05, those three become one batched round trip. Removing a line through removeLine produces one DELETE for that line plus UPDATEs to line_no for any lines after it (the price of an ordered list), and one UPDATE to orders for the total and the version. Paying an order is exactly one UPDATE with WHERE id = ? AND version = ?. Nothing here ever touches product, because no cascade points at it.

Choosing an id strategy — the trade-offs that decide it.
Choose…WhenCost you acceptAvoid when
SEQUENCE, allocationSize 50PostgreSQL, Oracle, SQL Server; any workload with bulk insertsGaps in ids after restarts (a block of 50 is abandoned); sequence must match the incrementThe database has no sequences (MySQL)
IDENTITYMySQL/MariaDB; simple CRUD services with no bulk writesNo JDBC batching of INSERTs; INSERT runs at persist() timeImports, event ingestion, anything that writes thousands of rows per transaction
Time-ordered UUID (v7)Ids must be generated by the client, across shards or regions, or before the row exists16 bytes per key and per secondary index entry; ids are not human-readableKeys are user-visible and expected to be short, or the database is a legacy one without a native uuid type
Random UUID (v4)Almost never for a primary keyRandom B+tree inserts fragment the primary index and wreck the buffer cache at scaleAny table expected to exceed a few million rows
TABLENever in new codeEvery id allocation locks one row in a shared table — a global serialization pointAlways; use SEQUENCE or IDENTITY per engine

Quick reference — Mapping and ownership

IDENTITY vs SEQUENCE
IDENTITY needs the insert to happen immediately to learn the key, so it cannot be JDBC-batched. SEQUENCE with an allocation size fetches keys ahead and batches freely.
owning side
The side with the foreign key — the one without mappedBy. Only changes to the owning side are written. Updating the other side alone does nothing.
cascade
Repeats an operation on related entities. CascadeType.ALL includes remove, which is how a delete quietly takes half the graph with it.
orphanRemoval
Deletes a child when it is removed from the parent's collection. Different from cascade: it fires on removal from the collection, not on an operation on the parent.
@Version
Optimistic locking. Hibernate adds WHERE version = ? and throws if zero rows updated — that is the lost update, caught.
Optimistic vs pessimistic
Optimistic assumes conflicts are rare and detects them at write. Pessimistic locks the row up front. Choose by how often you actually collide.

04 · The primerFetching & the N+1 Problem

One query for the parents, then one more per parent. That is the N+1 problem, it is the most common performance bug in JPA, and there are four fixes with a clear order of preference.

The number to remember is 1,201. An orders report loads 1,200 paid orders with one query, then, while building each row of the report, touches order.getLines(). Each touch is a new SELECT, because the lines were not loaded with the order.

The endpoint issues 1 + 1,200 queries, each a network round trip of about 0.5 milliseconds on a good day, and the page takes 600 milliseconds where it should take 15.

That is the N+1 problem, and the reason it is the single most common Hibernate incident is that the Java code looks completely innocent: a loop, a getter, nothing more.

You already know the idea from HTTP: fetching a list of 1,200 items and then calling a detail endpoint for each one is the same anti-pattern, and the cure is the same — ask for what you need in one request, or in a small fixed number of requests. The difference with Hibernate is that the extra requests are invisible until you look at the SQL log. So the first discipline of this chapter is: always know how many statements your method issues, and make a test fail when the count grows.

LAZY versus EAGER, and what a proxy is

Every relationship has a fetch type. EAGER means "load this related data whenever you load me". LAZY means "give me a placeholder now and load the real data only when someone touches it".

The JPA defaults are the wrong way round for production: to-one relationships (@ManyToOne, @OneToOne) default to EAGER, and collections (@OneToMany, @ManyToMany) default to LAZY. An EAGER to-one is a hidden join or a hidden extra query on every load, including loads that only needed the id, and it compounds: an order eagerly loading its customer, which eagerly loads its address, which eagerly loads its country, is four tables for one lookup.

The professional rule is: map everything LAZY, then decide per query what to fetch.

The placeholder for a lazy to-one is a proxy: a runtime-generated subclass of the entity that holds only the id and knows how to load the rest on first access.

For a lazy collection, the placeholder is a PersistentBag or PersistentSet that loads its contents on first iteration.

Both placeholders remember the persistence context that created them, and that memory is the whole LazyInitializationException story: if the context has closed — the transaction ended, the entity is detached — the proxy has no session through which to run its SELECT, and it throws LazyInitializationException: could not initialize proxy - no Session.

The exception "only in production" is almost always open-session-in-view being on in one environment and off in another, or a controller that serialises an entity to JSON after the transaction closed.

The four fixes, in the order you should reach for them

  1. JOIN FETCH. In JPQL, select o from Order o join fetch o.lines where o.status = :status loads orders and their lines in one SQL join. Hibernate 6 removed the old need for distinct to deduplicate parents, and the query returns each order once with its lines populated. Two limits: fetching two collections of type List in one query fails with MultipleBagFetchException (use Set, or fetch them in two queries), and fetching a collection while paginating is the trap in the next heading.
  2. Entity graphs. An @EntityGraph(attributePaths = {"lines", "customer"}) on a Spring Data method, or a jakarta.persistence.fetchgraph hint, is JOIN FETCH declared as metadata instead of written in the query. It is the right tool when the same base query needs different fetch shapes for different callers.
  3. Batch fetching. @BatchSize(size = 50) on the collection, or globally hibernate.default_batch_fetch_size: 50, changes the lazy load from one SELECT per parent into one SELECT per 50 parents using WHERE order_id IN (?, ?, ... ?). It turns N+1 into N/50+1 without changing any query, and it is the pragmatic global fix for a codebase with many lazy loops. Hibernate 6 pads the IN list to a few fixed sizes so the database's statement cache is not flooded with distinct shapes.
  4. DTO projections. If the report needs four columns, select four columns: select new com.shopstream.orders.OrderSummary(o.id, o.status, o.total.amount, size(o.lines)), or a Spring Data interface projection, or a Java record. No entities are loaded, no persistence context bookkeeping happens, nothing can lazy-load later, and the query returns exactly the bytes the screen needs. For read-heavy endpoints this is the best answer, not a fallback.
Lazy loop: 1 + N round trips select ... from orders where status = 'PAID' select ... from order_line where order_id = 1 select ... from order_line where order_id = 2 select ... from order_line where order_id = 3 … × 1,200 1,201 statements · ~600 ms join fetch: 1 round trip select o.*, l.* from orders o join order_line l on l.order_id = o.id where o.status = 'PAID' or @BatchSize(50): 1 + N/50 statements where order_id in (?, ?, … 50 ids) 1 statement · ~15 ms (or 25 with batching)
Fig. E5.3 — The same report, two fetch plans. The lazy loop sends one statement per order; the join fetch (highlighted) sends one statement for all of them; batch fetching sits in between and needs no query change.

Pagination with collections: the in-memory paging trap

Combine join fetch o.lines with setMaxResults(20) and you get a warning that has ended careers: HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory (the same warning was numbered HHH000104 in Hibernate 5). The reason is arithmetic. A join returns one row per line, not per order, so "20 rows" of the join might be three orders and a half — which would give the last order an incomplete collection. Hibernate refuses to hand you a half-loaded collection, so it drops the SQL LIMIT, pulls every matching order and every line into memory, and paginates the Java list. Page 1 of 20 orders costs the same as loading all 400,000. The fix is two queries: first select the page of order ids with an ordinary LIMIT, then join fetch the lines for where o.id in (:ids). Spring Data's Page with an @EntityGraph falls into the same trap, so paginate the parent alone and let @BatchSize fetch the collections.

Open-session-in-view, and why to turn it off

Open-session-in-view (OSIV) exists so that a JSP or a JSON serialiser can touch lazy fields after the service's transaction ended.

It solves the exception by moving the query somewhere worse: into the view layer, outside any transaction, with no batching, no fetch plan, and — because each lazy load needs a JDBC connection — a connection re-borrowed from the pool while the response is being rendered or while a slow downstream call is in flight.

Under load that pins pool connections behind non-database work and turns into pool exhaustion that looks like a database problem. Set spring.jpa.open-in-view: false, let LazyInitializationException surface in tests, and fix each one with one of the four fixes above.

Every one of those exceptions is an N+1 you would otherwise have shipped.

Seeing it: the report, before and after

Step-by-step: what OrderRepository.java and OrderReportService.java do, in plain English
  1. findByStatus is a derived query: Spring Data parses the method name into select o from Order o where o.status = ?1. It loads orders only; lines stay lazy.
  2. findWithLinesByStatus is the same query with join fetch o.lines written explicitly, so lines come back in the same statement.
  3. findSummaries is a projection: it builds OrderSummary records directly from four expressions, never loading an entity at all.
  4. slowReport loops over the lazy orders and touches getLines() — the lazy collection loads on first iteration, once per order. That is the N+1.
  5. fastReport runs the join-fetch query, so the same loop touches collections that are already loaded and issues no further SQL.
  6. projectionReport skips entities entirely; it is the cheapest shape for a read-only screen.
  7. All three methods are readOnly = true: Hibernate keeps no snapshots, and the transaction manager tells the JDBC driver the connection is read-only.
  8. The Statistics line at the end of each method prints how many statements Hibernate actually prepared — the number you would assert on in a test.
OrderRepository.java · OrderReportService.javaruns offline
// ---- OrderRepository.java ----
package com.shopstream.orders;

import java.math.BigDecimal;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface OrderRepository extends JpaRepository<Order, Long> {

    /** Derived query: orders only; lines stay lazy. This is the N+1 shape. */
    List<Order> findByStatus(Order.Status status);

    /** One statement: orders joined to their lines. */
    @Query("select o from Order o join fetch o.lines where o.status = :status")
    List<Order> findWithLinesByStatus(Order.Status status);

    /** Projection: no entities, no persistence-context bookkeeping. */
    record OrderSummary(Long id, Order.Status status, BigDecimal total, long lineCount) { }

    @Query("""
           select new com.shopstream.orders.OrderRepository$OrderSummary(
               o.id, o.status, o.total.amount, size(o.lines))
           from Order o where o.status = :status
           """)
    List<OrderSummary> findSummaries(Order.Status status);
}

// ---- OrderReportService.java ----
package com.shopstream.orders;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderReportService {

    private static final Logger log = LoggerFactory.getLogger(OrderReportService.class);

    private final OrderRepository orders;

    @PersistenceContext
    private EntityManager em;

    public OrderReportService(OrderRepository orders) {
        this.orders = orders;
    }

    @Transactional(readOnly = true)
    public int slowReport() {
        Statistics stats = statistics();
        stats.clear();
        int lineCount = 0;
        for (Order order : orders.findByStatus(Order.Status.PAID)) {
            lineCount += order.getLines().size();          // lazy load: one SELECT per order
        }
        log.info("slowReport: {} lines, {} statements", lineCount, stats.getPrepareStatementCount());
        return lineCount;
    }

    @Transactional(readOnly = true)
    public int fastReport() {
        Statistics stats = statistics();
        stats.clear();
        int lineCount = 0;
        for (Order order : orders.findWithLinesByStatus(Order.Status.PAID)) {
            lineCount += order.getLines().size();          // already loaded: no SQL
        }
        log.info("fastReport: {} lines, {} statements", lineCount, stats.getPrepareStatementCount());
        return lineCount;
    }

    @Transactional(readOnly = true)
    public long projectionReport() {
        Statistics stats = statistics();
        stats.clear();
        long lineCount = orders.findSummaries(Order.Status.PAID).stream()
                               .mapToLong(OrderRepository.OrderSummary::lineCount).sum();
        log.info("projectionReport: {} lines, {} statements", lineCount, stats.getPrepareStatementCount());
        return lineCount;
    }

    private Statistics statistics() {
        // Requires spring.jpa.properties.hibernate.generate_statistics=true (see application.yml).
        return em.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
    }
}
report.log — 1,200 paid orders, org.hibernate.SQL at DEBUG (repeated lines collapsed)
select o1_0.id,o1_0.created_at,o1_0.customer_id,o1_0.status,o1_0.total_amount,o1_0.total_currency,o1_0.version from orders o1_0 where o1_0.status=?
select l1_0.order_id,l1_0.line_no,l1_0.id,l1_0.product_id,l1_0.quantity,l1_0.unit_price from order_line l1_0 where l1_0.order_id=?
select l1_0.order_id,l1_0.line_no,l1_0.id,l1_0.product_id,l1_0.quantity,l1_0.unit_price from order_line l1_0 where l1_0.order_id=?
   ... (1,198 more identical statements with different ids)
slowReport: 3847 lines, 1201 statements

select o1_0.id,o1_0.created_at,o1_0.customer_id,l1_0.order_id,l1_0.line_no,l1_0.id,l1_0.product_id,l1_0.quantity,l1_0.unit_price,o1_0.status,o1_0.total_amount,o1_0.total_currency,o1_0.version from orders o1_0 join order_line l1_0 on o1_0.id=l1_0.order_id where o1_0.status=?
fastReport: 3847 lines, 1 statements

select o1_0.id,o1_0.status,o1_0.total_amount,(select count(1) from order_line l1_0 where o1_0.id=l1_0.order_id) from orders o1_0 where o1_0.status=?
projectionReport: 3847 lines, 1 statements

Read the output. The first block is the N+1 in the flesh: one SELECT on orders, then 1,200 SELECTs on order_line that differ only in the bound id, and a statistics line that says 1201 statements — the number a test should assert on. The second block is the join fetch: one wide statement that carries columns from both tables, the same 3,847 lines, one statement. Notice the SQL has no distinct; Hibernate 6 deduplicates parents in memory automatically. The third block is the projection: a narrow statement with a correlated subquery for the line count, and no entity ever instantiated — if this method were called from a controller after the transaction ended, there would be nothing to lazy-load and nothing to detach. Which of the three you pick is a per-endpoint decision: entities when you are about to change them, join fetch when you need the graph, projections when you only need to read.

There are no dumb questions

If LAZY is so dangerous, why not make everything EAGER and be done with it?
Because EAGER is worse in a way you cannot fix per query. A LAZY relationship can be fetched eagerly for the one query that needs it, using join fetch or an entity graph. An EAGER relationship is loaded for every query that touches the entity, including the ones that only wanted an id, and there is no per-query way to turn it off. EAGER on a to-one is a hidden join on every load; EAGER on two collections is a Cartesian product. LAZY plus explicit fetching per query is the only combination where you control the SQL.
Does join fetch always beat batch fetching?
No. Join fetch sends one statement but repeats every parent column once per child row, so an order with 200 lines transfers the order's columns 200 times. Batch fetching sends a few more statements but each row is transferred once. For small collections join fetch wins; for wide parents with big collections, or when you need pagination, batch fetching wins. Measure the bytes on the wire, not just the statement count.
My controller returns the entity directly as JSON. Where should I put the fetching?
Stop returning entities from controllers. The serialiser will walk every getter, trigger every lazy collection it can reach, and either throw LazyInitializationException or, with OSIV on, issue a shower of queries after your transaction closed. Return a DTO built inside the transaction — a record — so the boundary of what is loaded is explicit and the JSON shape is not coupled to the table shape. E6 on API design covers the contract side of that decision.
What is the difference between a fetch graph and a load graph?
A jakarta.persistence.fetchgraph says "fetch exactly these attributes eagerly and treat everything else as lazy", regardless of the mapping. A jakarta.persistence.loadgraph says "fetch these eagerly in addition to whatever the mapping already says is eager". Spring Data's @EntityGraph defaults to fetch graph semantics. In practice, if you followed the rule that everything is mapped LAZY, the two behave the same.

Quick reference — Fetching and N+1

N+1
One query for the parents, then one per parent for its children. The default behaviour of a lazy association in a loop.
LAZY vs EAGER
LAZY is right almost always. EAGER on a @ManyToOne means every query for that entity joins, whether you needed it or not.
proxy
What a lazy association really holds: a subclass that loads the real object on first access. Touch it outside the context and you get LazyInitializationException.
The four fixes, in order
1. DTO projection — fetch only the columns you need. 2. Entity graph. 3. JOIN FETCH. 4. Batch fetching (@BatchSize) when the others do not fit.
The pagination trap
JOIN FETCH on a collection plus setMaxResults makes Hibernate fetch every row and paginate in memory. It warns; the warning is real.

05 · The primerBatching, Caches & Session Types

Three levers, once the mapping is right: batching many statements into one round trip, keeping the persistence context from growing without bound, and caching what genuinely does not change.

A bulk import of five million product rows takes six hours. The engineer who wrote it did nothing obviously wrong: a loop, repository.save(product), one @Transactional method. Do the arithmetic and the six hours explain themselves.

Five million INSERTs, each a separate round trip at about 4 milliseconds through the pool and across the network, is 20,000 seconds — five and a half hours — before the database has done any real work.

Meanwhile the persistence context holds five million managed entities and five million snapshots, so the heap fills, garbage collection pauses stretch, and the last hour is spent mostly collecting garbage.

The same import, written with JDBC batching, a sequence id, and a flush-and-clear every 500 rows, runs in about eight minutes. Nothing about the database changed; only the shape of the conversation with it.

The bridge: you already batch network calls. Nobody sends 5 million HTTP requests when a bulk endpoint exists. A JDBC batch is the bulk endpoint of the database protocol — many statements of the same shape, one round trip — and this chapter is about letting Hibernate use it, plus the two caches that sit beside the persistence context and the one session type that skips it.

JDBC batching: the settings and the traps

Hibernate batches statements at flush time when three conditions hold. First, hibernate.jdbc.batch_size is set (there is no default; 20 to 100 is the useful range, and 50 is the common choice).

Second, the statements are the same kind on the same table in a row — hibernate.order_inserts: true and hibernate.order_updates: true reorder the flush queue so that INSERTs for orders are grouped together, then INSERTs for lines, instead of interleaved by the order your code created them.

Third, the id strategy does not force immediate execution — which is the IDENTITY story from chapter 03 again: identity columns need the INSERT's result before the next entity can be managed, so identity inserts are never batched, whatever the property says.

Two driver-level flags decide whether a JDBC batch is really one round trip. PostgreSQL's driver batches at the protocol level already, and reWriteBatchedInserts=true on the URL additionally rewrites the batch into one multi-row INSERT ... VALUES (...), (...), (...), which is roughly two to three times faster again.

MySQL Connector/J does not batch by default — it sends the statements one by one and merely pretends — until you add rewriteBatchedStatements=true to the URL. Forgetting that flag is why a MySQL team can set every Hibernate property correctly and see no improvement at all.

hibernate.jdbc.batch_versioned_data (true by default since Hibernate 5) lets UPDATEs with a @Version check be batched; Hibernate reads the per-statement update counts from the batch result to detect a stale version, which every current driver supports.

flush queue (code order) insert orders #1 insert order_line #1a insert order_line #1b insert orders #2 insert order_line #2a insert orders #3 order_inserts=false batch breaks on every table change 6 batches of 1 = 6 trips order_inserts=true orders #1 #2 #3 order_line #1a #1b #2a 2 batches = 2 trips database batch_size = 50 SEQUENCE ids only
Fig. E5.4 — The flush queue is written in the order your code ran. Without ordering, every switch between tables ends the current batch; with hibernate.order_inserts the queue is regrouped by table first, and the highlighted path sends two batches instead of six single statements.

The memory side: flush, clear, and the stateless session

Batching fixes the round trips but not the heap. Every persisted entity stays managed, with its snapshot, until the persistence context closes. The standard loop for a large import therefore calls em.flush() and em.clear() every batch_size rows: flush sends the pending batch, clear drops the managed entities so the garbage collector can have them. Commit every few thousand rows as well, so a failure at row four million does not roll back four million inserts and so the transaction does not pin undo space or old row versions for hours — the same batch-commit rule E8's transaction chapter gives from the database side.

Hibernate offers a cleaner tool for exactly this workload: the StatelessSession. It has no persistence context, no first-level cache, no dirty checking, no cascades, and no lazy loading — every insert(), update() and delete() is a direct statement, batched.

It is the right tool for imports, exports, and event ingestion, and the wrong tool for anything that relies on the object graph being managed.

Two Hibernate 7 changes matter here as of 2026: a stateless session now uses the second-level cache by default (disable it with setCacheMode(CacheMode.IGNORE) for a pure import), and hibernate.jdbc.batch_size no longer applies to it — you call session.setJdbcBatchSize(50) explicitly, as the import below does.

Step-by-step: what ProductImportService.java does, in plain English
  1. The service borrows the SessionFactory from the injected EntityManagerFactory; Spring Boot builds exactly one of each.
  2. importAll reads the CSV line by line through a BufferedReader, so a five-million-line file is never in memory at once.
  3. It opens a StatelessSession in a try-with-resources, sets the JDBC batch size on the session (required on Hibernate 7), and turns the second-level cache off for this session.
  4. Each chunk of CHUNK rows runs inside its own explicit transaction: beginTransaction, a loop of insert() calls, then commit. Sequence ids in blocks of 50 mean the inserts flush as batches of 50 with no per-row round trip.
  5. If a chunk fails, the exception rolls back only that chunk; the log records the line number so the file can be resumed, and the rows already committed stay committed.
  6. parse turns one CSV line into a transient Product — there is no persistence context, so "transient" is the only state the object ever has.
ProductImportService.javaruns offline
package com.shopstream.orders;

import jakarta.persistence.EntityManagerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.hibernate.CacheMode;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ProductImportService {

    private static final Logger log = LoggerFactory.getLogger(ProductImportService.class);
    private static final int BATCH = 50;       // rows per JDBC batch; matches allocationSize
    private static final int CHUNK = 5_000;    // rows per transaction; bounds rollback cost

    private final SessionFactory sessionFactory;

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

    /** Streams a CSV of "sku,name,price" lines into the product table. Returns rows written. */
    public long importAll(Path csv) throws IOException {
        long written = 0;
        try (BufferedReader in = Files.newBufferedReader(csv, StandardCharsets.UTF_8);
             StatelessSession session = sessionFactory.openStatelessSession()) {

            session.setJdbcBatchSize(BATCH);           // Hibernate 7: the global property no longer applies here
            session.setCacheMode(CacheMode.IGNORE);    // Hibernate 7: stateless sessions use the L2 cache by default

            String line;
            long lineNo = 0;
            Transaction tx = session.beginTransaction();
            try {
                while ((line = in.readLine()) != null) {
                    lineNo++;
                    if (line.isBlank() || lineNo == 1 && line.startsWith("sku,")) continue;   // skip header
                    session.insert(parse(line));       // direct INSERT, queued into the JDBC batch
                    written++;
                    if (written % CHUNK == 0) {
                        tx.commit();                   // flushes the open batch, releases locks, bounds the transaction
                        tx = session.beginTransaction();
                        log.info("committed {} rows (line {})", written, lineNo);
                    }
                }
                tx.commit();
            } catch (RuntimeException e) {
                tx.rollback();
                log.error("import failed at line {} after {} committed rows", lineNo, written - (written % CHUNK), e);
                throw e;
            }
        }
        return written;
    }

    private Product parse(String line) {
        String[] f = line.split(",", 3);
        return new Product(f[0].trim(), f[1].trim(), new BigDecimal(f[2].trim()));
    }
}

Read the shape rather than the output this time. The service never touches the persistence context, so its memory footprint is one chunk of 5,000 transient objects at most, and the garbage collector reclaims each chunk at commit. Each batch of 50 INSERTs is one round trip; each chunk of 5,000 rows is 100 round trips and one COMMIT. Five million rows is 100,000 round trips at 4 milliseconds — about seven minutes — plus one sequence call per 50 rows. The same import through repository.saveAll() in one transaction would be a single flush at the very end holding five million entities, and with IDENTITY ids it would be five million round trips whatever else you configured.

The second-level cache and the query cache

The first-level cache dies with the persistence context.

The second-level cache (L2) is shared across all persistence contexts in the JVM: an entity marked @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) is stored, after loading, in a region of a cache provider — JCache with Ehcache, Caffeine through a JCache adapter, or Infinispan — so that the next find() by id in any session comes from memory.

It helps exactly one access pattern: lookup by primary key of data that changes rarely and is read constantly — a product catalogue, a country table, feature flags.

It hurts in three situations: write-heavy entities, where every update invalidates and the cache thrashes; a multi-node deployment without a distributed cache, where node A serves stale data after node B's write until the entry expires; and queries, because the L2 only answers by-id loads — a JPQL query goes to the database regardless of what is cached, then hydrates entities from the cache one by one, which can be slower than the plain query.

The query cache (hibernate.cache.use_query_cache: true plus a per-query setCacheable(true)) stores result ids for a specific query and parameter set. Its invalidation rule is coarse: any write to any table the query touches, by any session, invalidates every cached result for that table through the update-timestamps region.

For a table that changes a few times a day it is excellent; for orders it is worthless, and for a table shared between two application instances without a distributed cache it is dangerous.

Turn it on per query, never globally, and only after statement logging has shown you the exact query it would save. Hibernate 6 and 7 both keep the cache behind the JCache or Infinispan modules; Spring Boot 4.x does not autoconfigure a provider for you.

Seeing what Hibernate does: logging and statistics

You cannot tune what you cannot see, and spring.jpa.show-sql is the wrong way to see it — it prints to standard out, unformatted, with no bind values, and it cannot be turned off per environment through logging config.

The right settings are logger levels: org.hibernate.SQL at DEBUG prints every statement through your logging framework; org.hibernate.orm.jdbc.bind at TRACE (the Hibernate 6 and 7 logger name; Hibernate 5 used org.hibernate.type.descriptor.sql) prints the bound parameter values; hibernate.generate_statistics: true makes the Statistics object real, and org.hibernate.stat at DEBUG logs a per-session summary of statements, cache hits, flushes and time spent.

For tests, a datasource proxy — datasource-proxy or p6spy, both wrapped by the Hypersistence utilities SQLStatementCountValidator — lets you write assertSelectCount(1) and fail the build when an N+1 creeps in. That assertion is the cheapest performance test in the Java world.

Read-only transactions and connection handling

@Transactional(readOnly = true) does three things on Spring Boot with Hibernate. It sets the session's flush mode to MANUAL, so no dirty check or flush ever runs.

It marks loaded entities read-only, so Hibernate keeps no snapshots — roughly halving the memory per entity, which is why a report that loads 100,000 rows should always be read-only.

And it calls Connection.setReadOnly(true), which PostgreSQL uses to reject writes and which a routing datasource (or the AWS JDBC wrapper) uses to send the transaction to a read replica.

It is not a security control — a native UPDATE can still run on MySQL — but it is a performance control you should apply to every read path.

The connection pool is HikariCP, Spring Boot's default, with ten connections unless you set spring.datasource.hikari.maximum-pool-size. Two Hibernate settings decide how long a transaction holds one of those ten. By default Hibernate acquires the connection lazily at the first statement and releases it after the transaction ends.

Setting spring.datasource.hikari.auto-commit: false together with hibernate.connection.provider_disables_autocommit: true tells Hibernate the pool already hands out connections with autocommit off, so it need not borrow a connection at transaction start merely to call setAutoCommit(false); the connection is taken only when the first statement runs.

In a service that calls a slow remote API inside a transaction before its first query, that change alone can halve pool occupancy.

Fleet sizing — ten pool connections times forty pods is four hundred database sessions — belongs to E8's chapter on pools, and it is the single most common cause of "the database is slow" in Kubernetes-era systems.

Step-by-step: what application.yml does, in plain English
  1. The datasource URL carries reWriteBatchedInserts=true so the PostgreSQL driver turns each JDBC batch into one multi-row INSERT; the comment gives the MySQL equivalent.
  2. HikariCP hands out connections with autocommit off, and the pool size is explicit so nobody forgets it is ten.
  3. open-in-view: false ends the request-scoped persistence context; every lazy load outside a transaction now fails loudly in tests instead of running silently in production.
  4. ddl-auto: validate makes startup fail if the entities and the Flyway-managed schema disagree, and never lets Hibernate alter a production table.
  5. The hibernate.* properties turn on batching of 50 with ordered inserts and updates, enable statistics, and default batch fetching to 50 so lazy collections load in IN-lists.
  6. show-sql is left false; logging levels do the job properly, with bind values at TRACE only where you need them.
  7. Flyway is enabled with its default location, so migrations run before Hibernate validates the schema.
application.ymlruns offline
spring:
  datasource:
    # PostgreSQL. For MySQL use jdbc:mysql://db:3306/shopstream?rewriteBatchedStatements=true
    url: jdbc:postgresql://db:5432/shopstream?reWriteBatchedInserts=true
    username: ${DB_USER}
    password: ${DB_PASSWORD}
    hikari:
      maximum-pool-size: 10
      auto-commit: false
      connection-timeout: 3000
  jpa:
    open-in-view: false
    show-sql: false
    hibernate:
      ddl-auto: validate
    properties:
      hibernate:
        jdbc:
          batch_size: 50
          batch_versioned_data: true
        order_inserts: true
        order_updates: true
        default_batch_fetch_size: 50
        generate_statistics: true
        connection:
          provider_disables_autocommit: true
        query:
          fail_on_pagination_over_collection_fetch: true
  flyway:
    enabled: true
    locations: classpath:db/migration

logging:
  level:
    org.hibernate.SQL: DEBUG
    org.hibernate.orm.jdbc.bind: TRACE
    org.hibernate.stat: DEBUG

One line in that file deserves a closer look: hibernate.query.fail_on_pagination_over_collection_fetch: true. It turns the in-memory paging warning from chapter 04 into an exception, so the query that would have loaded 400,000 orders to show 20 fails in the test suite instead of in production. Settings that convert silent slowness into loud failure are the cheapest defence an ORM offers, and this file has three of them: that one, open-in-view: false, and ddl-auto: validate.

Boardroom translation

When a stakeholder asks why the team wants two weeks for "database performance work" on a service that already works, the pitch is this: "Our ORM currently talks to the database one row at a time. The nightly catalogue import takes six hours and blocks the morning price update; the orders report makes twelve hundred database calls per page. Batching and fetch tuning cut the import to under ten minutes and the report to one call — same hardware, no schema change, and it removes the two incidents that paged us last quarter." The ROI frame: a database round trip costs real money in cloud-managed instances, where IOPS and connection counts are billed, and every N+1 fixed lets the same database serve more traffic before the next instance-size upgrade, which for a managed PostgreSQL at production scale is typically a four-figure monthly line.

Quick reference — Batching, caches, sessions

JDBC batching
hibernate.jdbc.batch_size, plus ordered inserts and updates. Silently disabled by IDENTITY ids.
flush + clear
In a bulk loop, flush and clear every batch. Otherwise the persistence context holds every entity you touched, and the heap grows with the job.
StatelessSession
No persistence context, no dirty checking, no cache. The right tool for a bulk write where you do not need any of it.
second-level cache
Shared across transactions and sessions. Useful for genuinely static reference data; a source of stale-data bugs for anything else.
query cache
Caches result ids, and needs the second-level cache to resolve them. Easy to make slower than no cache at all.

06 · The primerMigrations, Schema Evolution & Spring Data JPA Specifics

Changing a live database without downtime, using versioned migration files and a four-step sequence that never leaves old and new code unable to run at the same time.

The most expensive Hibernate setting in the world is one word: spring.jpa.hibernate.ddl-auto: update. It asks Hibernate to compare your entities with the live database at startup and issue whatever ALTER TABLE statements it thinks close the gap.

It will add a column; it will never drop, rename, or narrow one; it will add a NOT NULL column with no default and fail on a populated table; it takes an exclusive lock on the table while it works; and it does all of this on every pod at the same moment during a rolling deploy.

Teams have lost hours of production availability to a startup that "just added an index".

The rule is absolute: update and create-drop are for a throwaway test database; production runs validate and every schema change is a versioned migration file that a human wrote and a reviewer read.

The bridge is version control. You would never let a build tool rewrite your source tree on the fly at deploy time; migrations put the schema under the same discipline — numbered, immutable once applied, reviewed, applied in order, and recorded in a history table so every environment can prove which version it is at.

Flyway and Liquibase

Flyway runs plain SQL files named V<version>__<description>.sql from classpath:db/migration, in version order, and records each in flyway_schema_history together with a checksum of the file.

On startup it applies any file not yet recorded; if a recorded file's checksum has changed, it refuses to start, because someone edited history.

Liquibase does the same job with a changelog in YAML, XML or SQL, adds a database-independent DSL and built-in rollback definitions, and is the choice when the same migrations must run on several database engines.

Both are autoconfigured by Spring Boot and run before Hibernate's schema validation, so a deploy with a missing migration fails fast at startup rather than at the first query.

Two Flyway mechanics matter for zero-downtime work: repeatable migrations (R__ prefix) rerun whenever their checksum changes, which is right for views and functions; and a script configuration file V12__add_index.sql.conf containing executeInTransaction=false, which is required for PostgreSQL's CREATE INDEX CONCURRENTLY, a statement that cannot run inside a transaction.

Zero-downtime schema changes: expand, migrate, contract

Two versions of your application run at once during every rolling deploy, so every schema change must be compatible with both the old and the new code at the same time. That constraint gives every risky change the same three-phase shape, called expand and contract. Renaming customer.display_name to customer.full_name looks like one statement, but a RENAME COLUMN breaks every old pod the instant it runs. The safe version takes four deploys:

  1. Expand. Add full_name as a nullable column. Deploy code that writes both columns and still reads the old one. Nothing old breaks; new rows have both values.
  2. Backfill. Copy display_name into full_name for existing rows in batches of a few thousand — never one UPDATE of the whole table, which would lock it and produce a transaction the size of the table. A repeatable batch loop keyed on the primary key, with a short sleep between batches, is the standard shape.
  3. Switch reads. Deploy code that reads full_name and still writes both. Add the NOT NULL constraint now, when every row is populated (PostgreSQL 12 and later validates a NOT NULL constraint without a full lock if you add it as a CHECK constraint NOT VALID first and validate separately).
  4. Contract. Deploy code that writes only full_name. Only then drop display_name — in its own migration, one release later, so a rollback of the previous release still finds its column.
deploys → 1 · Expand ADD COLUMN full_name (nullable) write: both read: display_name old pods still fine 2 · Backfill UPDATE … WHERE id BETWEEN ? AND ? 5,000 rows per batch short locks, resumable no deploy needed 3 · Switch reads read: full_name write: both add NOT NULL (validated separately) rollback still works 4 · Contract write: full_name only then, one release later: DROP COLUMN display_name nothing references it at every step, the previous release's code still runs against the current schema
Fig. E5.5 — Expand and contract for a column rename. The highlighted backfill phase is the one that touches every row, so it runs in small batches outside any deploy; each of the other three is a migration plus a code change that the previous release can survive.

The initial migration for the order model

Step-by-step: what V1__init_orders.sql does, in plain English
  1. Four sequences are created with INCREMENT BY 50, matching each entity's allocationSize; a mismatch makes Hibernate fail validation at startup.
  2. customer and product get their natural unique keys (email, sku) as real constraints, not just Java annotations.
  3. orders carries the embedded total_amount/total_currency pair, a status text column with a CHECK constraint listing the enum's names, a version column for optimistic locking, and a foreign key to customer.
  4. order_line has the owning-side foreign key order_id and the line_no column that backs @OrderColumn; the composite unique key on (order_id, line_no) makes a duplicate position impossible.
  5. Indexes are created on every foreign key column, because PostgreSQL does not create them automatically and a missing FK index makes deleting a parent a full scan of the child table.
  6. The composite index on (customer_id, status) matches the @Index declared on the entity and the "my orders by status" query the app runs most.
src/main/resources/db/migration/V1__init_orders.sqlruns offline
-- Sequences must match @SequenceGenerator(allocationSize = 50) exactly.
CREATE SEQUENCE customer_seq   START WITH 1 INCREMENT BY 50;
CREATE SEQUENCE product_seq    START WITH 1 INCREMENT BY 50;
CREATE SEQUENCE orders_seq     START WITH 1 INCREMENT BY 50;
CREATE SEQUENCE order_line_seq START WITH 1 INCREMENT BY 50;

CREATE TABLE customer (
    id           BIGINT        PRIMARY KEY,
    version      BIGINT        NOT NULL DEFAULT 0,
    email        VARCHAR(254)  NOT NULL,
    display_name VARCHAR(120)  NOT NULL,
    CONSTRAINT uq_customer_email UNIQUE (email)
);

CREATE TABLE product (
    id    BIGINT         PRIMARY KEY,
    sku   VARCHAR(32)    NOT NULL,
    name  VARCHAR(200)   NOT NULL,
    price NUMERIC(19, 4) NOT NULL,
    CONSTRAINT uq_product_sku UNIQUE (sku)
);

CREATE TABLE orders (
    id             BIGINT         PRIMARY KEY,
    version        BIGINT         NOT NULL DEFAULT 0,
    customer_id    BIGINT         NOT NULL,
    status         VARCHAR(16)    NOT NULL,
    total_amount   NUMERIC(19, 4) NOT NULL,
    total_currency VARCHAR(3)     NOT NULL,
    created_at     TIMESTAMP WITH TIME ZONE NOT NULL,
    CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customer (id),
    CONSTRAINT ck_orders_status CHECK (status IN ('NEW', 'PAID', 'SHIPPED', 'CANCELLED'))
);

CREATE TABLE order_line (
    id         BIGINT         PRIMARY KEY,
    order_id   BIGINT         NOT NULL,
    line_no    INTEGER        NOT NULL,
    product_id BIGINT         NOT NULL,
    quantity   INTEGER        NOT NULL CHECK (quantity > 0),
    unit_price NUMERIC(19, 4) NOT NULL,
    CONSTRAINT fk_order_line_order   FOREIGN KEY (order_id)   REFERENCES orders (id),
    CONSTRAINT fk_order_line_product FOREIGN KEY (product_id) REFERENCES product (id),
    CONSTRAINT uq_order_line_position UNIQUE (order_id, line_no)
);

-- PostgreSQL does not index foreign keys for you; without these, deleting a parent scans the child table.
CREATE INDEX ix_orders_customer_status ON orders (customer_id, status);
CREATE INDEX ix_order_line_order       ON order_line (order_id);
CREATE INDEX ix_order_line_product     ON order_line (product_id);

Read it against the entities. Every nullable = false in Java has a NOT NULL here; every unique = true has a named constraint; the Instant createdAt field maps to TIMESTAMP WITH TIME ZONE, which is what Hibernate 6.2 and later expect for Instant — Hibernate 7's stricter schema validation rejects a plain TIMESTAMP for an Instant field, and that mismatch is the most common validation failure teams hit when upgrading from Boot 3 to Boot 4. With ddl-auto: validate, every one of those correspondences is checked at startup, so the migration and the mapping cannot drift apart silently.

Spring Data JPA specifics that interviewers ask about

Derived queries like findByCustomerIdAndStatusOrderByCreatedAtDesc are parsed from the method name at startup into JPQL; they are excellent for two or three conditions and unreadable beyond that, at which point @Query with explicit JPQL is clearer and, unlike a derived query, can join fetch.

Specifications (JpaSpecificationExecutor) build the criteria API's predicate tree at runtime for search screens with optional filters — the one place where dynamic query composition is legitimately needed. Projections — interface-based, class-based (records), or dynamic via a Class<T> parameter — return exactly the selected columns.

@Modifying marks a @Query as an UPDATE or DELETE; pair it with clearAutomatically = true, because a bulk JPQL update bypasses the persistence context, and any entity already loaded in the same transaction keeps its stale values until cleared.

It also bypasses @Version unless the JPQL says update versioned Order o set ..., a Hibernate extension.

save() is the method everybody uses and few can explain. SimpleJpaRepository.save checks isNew(): by default an entity is new when its id is null (or its primitive id is zero, or its @Version is null for wrapper types). If new, it calls persist().

If not, it calls merge() — which first issues a SELECT to load the current row, copies your object's state onto the managed copy, and returns that copy. Two consequences follow.

First, calling save() on an entity you loaded in the same transaction is redundant: it is already managed, and dirty checking will write it — the call costs nothing but is a sign the author does not trust the persistence context.

Second, saving an entity that has a pre-assigned id (a UUID you generated, a natural key) always hits the merge path and pays a SELECT per row before every INSERT; the fix is to implement Persistable<ID> and return true from isNew() until the entity has been persisted once.

getReferenceById(id) returns a proxy without a SELECT, which is the right way to set a foreign key when you have the id and do not need the row.

Repository methods are transactional by default: SimpleJpaRepository is annotated @Transactional(readOnly = true) at the class level with the writing methods overridden as read-write. That is why a bare repository call outside any service transaction works — and why lazy loading immediately afterwards does not, because the repository's transaction ended when the method returned. E4 explains the proxy chain that makes the service-level @Transactional the one that should win.

What changed in Hibernate 7 and Jakarta Persistence 3.2 (as of August 2026)

Spring Boot 4.0 shipped in November 2025 on Spring Framework 7, Jakarta EE 11, and Hibernate 7.1, and the 4.x line tracks Hibernate 7.2 and later through 2026; Spring Boot 3.5 remains on Hibernate 6.6 for teams not yet migrated. The changes an interviewer may probe:

When to use JPA/Hibernate, when to reach for something else — the decision.
Choose…WhenBecauseDo not choose it when
JPA entities with Spring DataA rich domain model with invariants; CRUD-heavy services; the graph is edited in memory then savedDirty checking, cascades and optimistic locking do the bookkeeping you would otherwise hand-writeThe workload is mostly reporting, or the "entities" are just rows with no behaviour
JPQL/native projections to recordsRead-heavy endpoints, reports, list screensExactly the columns needed, no persistence-context cost, no lazy-load riskYou intend to modify the rows you read
jOOQ or plain JDBC (JdbcClient)Complex SQL — window functions, CTEs, engine-specific features; analytics; teams fluent in SQLType-safe SQL you can read and EXPLAIN as written; no hidden fetch planThe model has deep object graphs that are edited transactionally — you would rewrite dirty checking by hand
StatelessSession or batch JDBCImports, exports, event ingestion in the millions of rowsNo first-level cache, no snapshots, straight batched statementsAny code path that relies on cascades, lazy loading or the identity map
No ORM: stored procedures / bulk SQLSet-based transformations of whole tables; month-end batch; data migrationsOne statement in the database beats a million statements from the application, alwaysBusiness logic would end up split between Java and SQL with no clear owner
🧠 Brain power

Before the drill: your team wants to add a mandatory region column to orders (200 million rows, PostgreSQL 16), defaulting to 'EU'. Someone proposes one migration: ALTER TABLE orders ADD COLUMN region VARCHAR(8) NOT NULL DEFAULT 'EU'. Is that safe for a rolling deploy, and what is the one change to the Java side that must ship before the migration?

Reveal the answer

On PostgreSQL 11 and later, adding a NOT NULL column with a constant default is a metadata-only change: the default is stored in the catalogue and applied on read, no rows are rewritten, and the lock is held for milliseconds — so the migration itself is safe.

(On MySQL 8 the equivalent is an ALGORITHM=INSTANT add, also safe.) The trap is on the Java side. With ddl-auto: validate, the new column is harmless to old pods, because Hibernate validates only that mapped columns exist, not that unmapped ones do not.

But the moment the new entity mapping ships, any INSERT from Hibernate must include region or rely on the database default — and Hibernate's INSERT lists every mapped column and writes NULL for an unset field, which violates NOT NULL. So the new code must either set region in the constructor, or mark the field @Column(insertable = false) with @Generated until every writer sets it, or use @DynamicInsert.

Ship the migration first (old code ignores the column), then the code that populates it; never the reverse, or every pod running the new code fails validation at startup because the column it maps does not exist yet.

Quick reference — Migrations and schema evolution

Flyway / Liquibase
Versioned migration files, applied in order, recorded in a table. Never hbm2ddl.auto=update in production.
expand and contract
The four steps that give zero downtime: Expand (add the new thing, nullable) → Backfill → Switch reads → Contract (drop the old thing), each a separate deploy.
Why four deploys
Because at every moment, the currently running code and the next version must both work against the schema as it is.
Derived queries
findByStatusAndCreatedAtAfter — Spring Data parses the method name and writes the query. Fine until the name gets long enough to need a comment.
@Modifying
Required on a repository @Query that writes. Add clearAutomatically or the persistence context now disagrees with the database.

07 · DrillPersistence Context, Entity Lifecycle & Transactions — Q1–Q40

The persistence context is where senior Hibernate rounds are decided, because every follow-up — "and when does that SQL go out?", "and what if the transaction has already ended?" — comes back to it. These forty questions drill the identity map, the four entity states, flush timing and dirty checking, how a Spring transaction owns a session, and the merge-versus-persist story behind save(). Answer out loud before revealing; the ordering of your reasoning is the answer.

Drill · Identity map & entity states

This group tests whether you can say, for any object in a method, which state it is in and what Hibernate will therefore do with it at flush — not whether you can list the four state names.

Q1. "What is the persistence context, concretely — what data structure is it, and what two guarantees does it give?"

Reveal answer

The real test Whether you describe a map with a key, or wave at "a cache".

Strong answer The persistence context is a map owned by one EntityManager (Hibernate's Session) and scoped to one unit of work, usually one transaction.

Its key is the pair of entity class and primary key; its value is the managed entity instance plus a snapshot of the field values as they were when loaded.

The first guarantee is identity: within one context, every load of customer 42 returns the same Java object, and the second load never touches the database — that is why it is also called the first-level cache.

The second guarantee is automatic write-back: any change to a managed object's fields is detected at flush by comparing against the snapshot, and turned into an UPDATE without any explicit call.

Both guarantees end when the context closes; from then on the objects are detached and nothing watches them. The map also holds the action queue — pending inserts, updates, deletes and collection changes — which is what a flush drains.

Land it Say "identity map keyed by class and id, with snapshots and an action queue" and every later question about flush, merge and lazy loading falls into place.

Likely follow-ups
"How would you prove, in a running service, that the identity map is actually returning the same object?"

I would turn on spring.jpa.properties.hibernate.generate_statistics=true and read the session statistics after the transaction: getEntityLoadCount() counts rows actually read from JDBC, while getEntityFetchCount() counts loads that had to go to the database because the entity was not already in the context.

If two findById(17) calls in one transaction produce a fetch count of one, the second was served from the map. The cheaper proof is a unit test: load the entity twice inside a TransactionTemplate and assert assertSame(a, b), not assertEquals.

And in Hibernate 7, which Spring Boot 4 ships as of Aug 2026, session.getManagedEntities() lets the test print exactly what the context holds at that moment.

"What is the memory cost of the persistence context, per entity?"

Each managed entity costs the entity object itself, plus an EntityEntry record, plus the loaded-state snapshot, which is an Object[] with one slot per mapped attribute.

For an entity with twenty columns the snapshot roughly doubles the footprint, because every boxed value is held twice — once in the field and once in the array. Collections add a PersistentCollection wrapper and their own snapshot of the loaded elements.

So a transaction that loads 100,000 order lines with ten fields each holds something like 200,000 objects plus 100,000 arrays before it does any work. That is why read paths should be readOnly = true, which skips the snapshot, and why batch loops must clear(). I would measure it with a heap histogram filtered on org.hibernate.engine.internal.EntityEntryContext.

"Is the persistence context the same thing as the second-level cache?"

No, and confusing them is a common interview miss. The persistence context is the first-level cache: one per EntityManager, scoped to a transaction, holding live entity objects, always on, and impossible to disable.

The second-level cache is shared across all sessions in the process, is off by default, needs a provider such as JCache with Ehcache or Infinispan, and stores dehydrated state — arrays of column values keyed by id — not entity objects.

A hit in the second-level cache still builds a fresh managed instance in your persistence context.

They also differ in correctness risk: the first-level cache cannot be stale within a transaction, whereas the second-level cache can be stale when another process writes the same row, which is why it belongs only on reference data with a defined expiry.

"What happens to the persistence context if the transaction rolls back?"

Hibernate does not rewind the objects. After a rollback, the entities keep whatever field values your code set, but the database does not have them, and the JPA specification says the persistence context is now in an undefined state and should be discarded.

Spring does exactly that: JpaTransactionManager closes the EntityManager on completion, so every entity becomes detached with in-memory values that never reached the database.

The practical trap is code that catches the exception, holds on to the entity, and passes it to another transaction expecting it to be consistent; with @Version the version in the object is also stale, so the next merge fails.

The rule I apply is that after a rollback you reload everything by id.

Q2. "Walk me through the four entity states and, for each transition, the exact call that causes it."

Reveal answer

Strong answer An object begins transient when constructed with new: no id, unknown to Hibernate. persist() makes it managed — it enters the identity map, gets an id from the generator, and is scheduled for INSERT. find(), getReference() and every query return managed objects directly.

A managed object becomes detached when the persistence context closes at commit, or on clear(), or on detach(entity); it keeps its id and data but is no longer watched.

merge(detached) does not re-attach that object — it loads or finds the managed copy, copies the detached state onto it, and returns the managed copy.

remove(managed) moves it to removed: still in the map, scheduled for DELETE, and calling persist() on a removed entity un-removes it before flush. refresh(managed) overwrites in-memory state from the database.

Finally, persist() on a detached object throws PersistentObjectException: detached entity passed to persist, which is the exception people hit when they set an id by hand and call save().

Land it The transition people get wrong is merge: it returns a different object, and the one you passed in stays detached.

Likely follow-ups
"Why does merge() return a different object instead of re-attaching the one I passed?"

Because the identity map may already hold an object for that id.

If your detached order 17 were simply re-inserted into the map, there could be two Java objects for one row in the same context, which breaks the single-object guarantee that every later dirty check depends on.

So the specification defines merge as a copy: find or load the managed instance, copy state onto it, return it. The object you passed stays detached and unwatched, which is why merge(order); order.setStatus(PAID); saves nothing.

Hibernate's older native Session.update() did re-attach the same instance, but it threw NonUniqueObjectException when the map already had one, and it was removed in Hibernate 6.0 because that failure mode was worse than the copy semantics.

"What does refresh() do to unflushed changes, and when would you actually call it?"

refresh(entity) issues a SELECT and overwrites every field of the managed object with the database's current committed values, discarding any unflushed change to that entity, and cascades along CascadeType.REFRESH. I call it in two situations.

First, after a bulk JPQL update or a native statement changed the row behind Hibernate's back, when I need that one entity current without clearing the whole context.

Second, after an INSERT where the database computed columns Hibernate did not know about — a trigger-set value or a default — although @Generated is the cleaner answer for that.

I would not use it as a "sync" step in normal service code; if I find myself needing it often, the transaction is doing two things that belong in two transactions.

"What is the fifth state people forget, and how does a proxy fit into these four?"

The state many people forget is removed being reversible: a removed entity is still managed until flush, and persist() cancels the removal.

Proxies fit in as managed objects with no data yet — a getReference() result is managed, has an id, sits in the identity map, and simply has not run its SELECT. It becomes an ordinary loaded entity on first access to a non-id property.

When the context closes, an uninitialised proxy becomes a detached proxy, and touching it throws LazyInitializationException. As of Aug 2026, Jakarta Persistence 3.2 adds EntityManager.isLoaded(entity) and Hibernate.isInitialized(proxy) has existed for years, so code that receives an unknown object can check before touching it.

"How does Spring Data's save() map onto these transitions?"

save() is not a fifth transition; it chooses between two of the four. SimpleJpaRepository.save calls entityInformation.isNew(entity): if the id is null, or a primitive id is zero, or a wrapper @Version is null, it calls em.persist and the transient object becomes managed.

Otherwise it calls em.merge and returns the managed copy, so the object you passed stays detached. That is why the return value of save() must always be used and the argument thrown away.

For a managed entity, the merge branch is a no-op that returns the same reference. Nothing in save() ever calls refresh, detach or remove; those are deleteById, delete, and direct EntityManager calls.

Q3. "Two repository calls in one transaction both load order 17. How many SELECTs run, and why is that a correctness feature rather than an optimisation?"

Reveal answer

Strong answer If both calls are findById(17), one SELECT runs: the second call finds the entry for (Order, 17) in the identity map and returns it without SQL. If the second call is a JPQL query — say findByStatus — the query itself always runs, because Hibernate cannot know what rows match without asking the database, but when the result contains order 17, Hibernate discards the fresh row data and returns the existing managed instance from the map.

That is the correctness feature: within one transaction there can only ever be one Java object for one row, so two parts of the code can never hold two disagreeing copies of order 17, and a change made through one reference is visible through the other.

Without this rule, a service that modified order 17 through one path and read it through another would flush two competing UPDATEs, or lose one change entirely. The saved SELECT is a side effect; the single-object invariant is the point.

Land it Queries always hit the database; the identity map decides which object you get back, not whether SQL runs.

Likely follow-ups
"What if the two calls are in different transactions on the same thread?"

Then two SELECTs run and you get two different objects. Each transaction owns its own EntityManager, so the identity map from the first is closed and gone by the time the second begins.

The two objects are independent copies of the row as it was at each load, so they can disagree if a write happened in between.

If a service method is not annotated @Transactional and calls the repository twice, that is exactly what happens, because SimpleJpaRepository opens a tiny transaction per call. The tell in the SQL log is two identical SELECTs a few milliseconds apart.

That is the case where a colleague says "the first-level cache is not working" — it is working, there are just two of them.

"Does the identity map apply to projections and DTO queries?"

No. The map is keyed by entity class and id, and it only holds entities.

A JPQL query that selects a constructor expression, a Spring Data interface projection, a Tuple, or scalar columns builds fresh objects straight from the result set on every execution and never consults the map. That has two consequences.

Projections always show the database's current committed state, so they can disagree with a managed entity you modified but have not flushed — except that AUTO flush mode flushes before the query if the tables overlap, which closes most of that gap.

And projections cost no snapshot, no dirty check and no memory in the context, which is why read-heavy endpoints should return them instead of entities.

"What if the second query returns order 17 but the database row changed in between — which values do I see?"

You see the old values. Hibernate reads the row from the result set, checks the identity map, finds the managed instance for (Order, 17), and returns that instance without copying the newer column values onto it.

The JPA specification allows this because within one persistence context the entity is the truth, not the row.

If you need the fresh values, call em.refresh(order), which overwrites the object and its snapshot from the database, or run the query with setHint(HibernateHints.HINT_READ_ONLY, true) in a separate read transaction.

With @Version the stale object is still safe: when your transaction tries to UPDATE it, the version check fails and you get an OptimisticLockException instead of a silent overwrite.

"How would you catch a regression where that single SELECT became two?"

I would add a statement-count assertion to the integration test for that service method. Hibernate's Statistics.getPrepareStatementCount() after clear() at the start gives an exact count; libraries like io.hypersistence:hypersistence-utils offer SQLStatementCountValidator.assertSelectCount(1), and the quickperf JUnit extension does the same with an annotation.

The regression usually comes from someone removing @Transactional from the service method or splitting the logic into two beans with separate transactions, so the count assertion fails the build before the N+1 reaches production.

In production, the leading indicator is hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS plus a query count per request exported through Micrometer.

Q4 · Scenario. "A developer loads an order, changes its status, and never calls save(). The change appears in the database anyway. Then, in another service, the same pattern does not save. Explain both."

Reveal answer

The real test Whether you diagnose by transaction boundary rather than by the presence of a save() call.

Strong answer Symptom: one method persists changes without save(), another does not. Evidence to collect: is each method inside a @Transactional boundary, and is the entity managed at the moment the field changes?

In the first service the load and the change happen inside one transaction, so the entity is managed; at commit the dirty check compares the status field against its snapshot, finds it changed, and issues the UPDATE. save() would have been a no-op.

In the second service, ranked by likelihood: the method is not transactional — the repository call ran in its own short transaction, the entity came back detached, and changing a detached object changes nothing; or the method is transactional but was self-invoked from the same class, bypassing the Spring proxy, so no transaction wrapped it (see E4); or the entity was loaded read-only, where Hibernate keeps no snapshot and never flushes.

Fix: put the transaction boundary around load-and-change, and check the proxy path. Prevention: a test that asserts the row changed, and open-in-view: false so detached entities fail loudly.

the update nobody wroteruns offline
@Transactional
public void confirm(Long id) {
    Order order = repo.findById(id).orElseThrow();   // MANAGED from here on
    order.setStatus(CONFIRMED);                       // just a setter
}                                                     // <- UPDATE runs HERE

// Hibernate SQL:
//   select o.* from orders o where o.id = ?
//   update orders set status = ?, ... where id = ?

// MECHANISM — automatic dirty checking:
// 1. On load, Hibernate stores a SNAPSHOT: a copy of every column value,
//    kept in the persistence context alongside the entity.
// 2. At flush (commit, or before a query that might be affected), it walks
//    every managed entity and compares each field against its snapshot.
// 3. Any difference produces an UPDATE. No save() call is involved anywhere.

// THE TWO CONSEQUENCES PEOPLE ARE SURPRISED BY:
//
// a) A change you did NOT intend to persist is persisted anyway:
@Transactional(readOnly = false)
public OrderDto get(Long id) {
    Order o = repo.findById(id).orElseThrow();
    o.setLastViewed(now());        // "just for the response" -> WRITES TO THE DATABASE
    return OrderDto.from(o);
}
//
// b) It costs. The snapshot doubles the memory per entity, and the comparison
//    is O(entities * fields) on EVERY flush -- which is the Q10 slowdown.

// TO AVOID IT DELIBERATELY: readOnly = true sets FlushMode.MANUAL, so no
// dirty checking runs at all. Or detach the entity, or map to a DTO in the query.

Case (a) is the one that causes production incidents. A field set for display purposes inside a read-write transaction is a real UPDATE, which is how a GET endpoint ends up writing to the database on every request.

Land it The question is never "did you call save" but "was the object managed when you changed it".

Likely follow-ups
"You said self-invocation bypasses the proxy. How would you confirm that is what happened?"

I would set a breakpoint or log line inside the method and check TransactionSynchronizationManager.isActualTransactionActive() at the moment the field changes — it returns false when the proxy was bypassed.

The stack trace is a second clue: a proxied call shows TransactionInterceptor.invoke and a CGLIB$$ frame above the method; a self-invoked call shows the calling method directly above it.

Turning on logging.level.org.springframework.transaction.interceptor=TRACE prints "Getting transaction for" and "Completing transaction for" per method name, so a missing pair is the proof. The fix is to move the method to another bean, inject the bean's own proxy with @Lazy self-injection, or use TransactionTemplate explicitly.

"The developer added @Transactional and it still does not save. What next?"

Then I check the remaining ways an entity is not watched. Was it loaded in a readOnly = true transaction, where Hibernate keeps no snapshot and never flushes? Is the class or the query marked @Immutable or given the HINT_READ_ONLY hint?

Is the entity actually the one in the context — a common miss is calling save() on a detached DTO-like copy and then editing the original. Is the field mapped at all, or annotated @Transient or updatable = false?

Did a checked exception cause a commit, or did a runtime exception cause a rollback that the caller swallowed? And finally, is the method on a class Spring is not proxying at all, such as a final class or a private method. Each one has a one-line test in the SQL log.

"Is relying on dirty checking without an explicit save() good practice, or should teams always call save() for clarity?"

I recommend relying on dirty checking and not calling save() on managed entities, and I would put it in the team's guidelines.

A redundant save() looks harmless but it cascades along MERGE relationships, which can initialise lazy collections just to discover nothing changed, and it teaches readers that persistence depends on the call rather than on the transaction boundary — so the one time an entity is detached, nobody notices.

The clarity argument is better served by naming: a service method called markPaid(orderId) that loads, mutates through a domain method, and returns tells the reader everything.

Where I do want an explicit call is creation, where persist() or save() is genuinely the transition that puts the object under management.

"What does readOnly do here exactly — would the change be silently dropped?"

Yes, silently. In a @Transactional(readOnly = true) method Spring's HibernateJpaDialect sets the session flush mode to MANUAL and setDefaultReadOnly(true), so loaded entities carry no snapshot and the commit runs no flush.

You can set fields all day and no UPDATE is ever generated; there is no exception because nothing is checked.

On PostgreSQL, Spring also calls Connection.setReadOnly(true), so a forced flush() would fail with "cannot execute UPDATE in a read-only transaction", which at least makes the mistake visible; on MySQL and Oracle the flag is a hint and the explicit flush would succeed.

The verification is the SQL log: no UPDATE after commit means the transaction was read-only, self-invoked, or absent.

Q5. "What does getReferenceById() return, when would you use it, and how can it blow up?"

Reveal answer

Strong answer getReferenceById(id) (JPA's getReference) returns a proxy — a generated subclass of the entity holding only the id — without running a SELECT. The proxy is managed, so you can hand it to a relationship: order.setCustomer(customerRepo.getReferenceById(customerId)) writes the foreign key on flush with no query for the customer row, which is exactly what you want when the request already carries the id.

It blows up in two ways. First, touching any non-id field initialises the proxy with a SELECT, and if the row does not exist you get EntityNotFoundException at that moment, not at the call — so a missing id surfaces at a surprising line.

Second, if the proxy escapes the transaction and is touched later, it throws LazyInitializationException like any other proxy.

One more subtlety: find() after getReference() for the same id returns the proxy, because the identity map already has an entry, so instanceof checks against the concrete class can fail on a proxy of a subclass.

getReferenceById returns a proxy, not a rowruns offline
Order order = repo.getReferenceById(17L);
// NO SELECT is issued. You get a lazy proxy: a generated subclass of Order
// with only the id populated.

order.getId();        // still no SELECT -- the id is known
order.getStatus();    // NOW the SELECT fires (or throws, see below)

// THE LEGITIMATE USE — setting a foreign key without loading the row:
@Transactional
public void assign(Long orderId, Long courierId) {
    Order order = repo.findById(orderId).orElseThrow();
    order.setCourier(courierRepo.getReferenceById(courierId));   // no SELECT on courier
}   // the UPDATE only needs the courier id, so loading the courier was pure waste

// THE TWO WAYS IT BLOWS UP:
//
// 1. THE ROW DOES NOT EXIST. findById returns an empty Optional immediately;
//    getReferenceById returns a proxy happily and throws
//    EntityNotFoundException LATER, at the first real access -- possibly in
//    a completely different method, or during JSON serialisation.
//
// 2. THE PROXY OUTLIVES THE TRANSACTION -> LazyInitializationException,
//    with the same "works locally, fails in production" shape as Q15.

// AND IT BREAKS instanceof / equals:
Object o = repo.getReferenceById(17L);
o.getClass();                  // com.acme.Order$HibernateProxy$xY7 -- NOT Order
o instanceof Order;            // true (it is a subclass)
o.equals(realOrder);           // false unless equals() unwraps the proxy
// Hibernate 6+ provides Hibernate.unproxy(o) for exactly this.

Failure 1 is what makes this dangerous in a REST layer. A missing row produces no error at the repository call and an EntityNotFoundException during serialisation instead — so the stack trace points at Jackson rather than at the lookup that was actually wrong.

Land it Use the reference when you need a foreign key, never when you need the data.

Likely follow-ups
"What happens if the referenced id does not exist and you only use it as a foreign key?"

Nothing fails until the flush. The proxy is created without a SELECT, the INSERT of the order carries customer_id = 999, and the database's foreign key constraint rejects it with a DataIntegrityViolationException at flush or commit time.

If there is no foreign key constraint in the schema, the row is inserted pointing at nothing, and the error surfaces much later as an EntityNotFoundException when something loads that order and touches its customer. So getReferenceById is safe only when a database constraint exists.

If the API must return a clean 404 for an unknown customer, I validate first with existsById, which is one cheap indexed SELECT, and keep the reference for the write.

"Why would instanceof fail on a proxy, and how do you unwrap it?"

A proxy is a runtime-generated subclass of the declared type — the field's type, not the row's real type.

If Payment has subclasses CardPayment and WalletPayment, a lazy order.getPayment() returns a proxy of Payment, so payment instanceof CardPayment is false even when the row is a card payment.

Hibernate provides Hibernate.unproxy(payment) (since 5.2), which initialises the proxy and returns the real instance, and Hibernate.getClass(entity) to get the concrete type without a cast.

The design answer is to avoid checking the type at all and put the behaviour on the entity through polymorphism, or to make the association eager with a join fetch so no proxy exists in the first place.

"How does getReferenceById interact with equals() and the identity map?"

The proxy goes into the identity map under (Customer, 42) like any managed entity, so a later findById(42) in the same transaction returns the same proxy object and initialises it with the SELECT that find runs. That preserves the single-object guarantee.

It also means the equals implementation matters: an id-based equals() that calls other.getId() works on a proxy, because the id accessor is answered without initialisation, but an implementation that reads other.id through the field directly sees null on a proxy and returns false.

That is why the standard advice is to compare through the getter, and why getClass() != other.getClass() checks must be replaced by Hibernate.getClass() or instanceof.

"Is there any cost to getReferenceById compared to find when you do need the data later?"

Slightly, yes. A proxy initialises with a SELECT by id at first access, which is the same statement find would have run, so the round-trip count is identical.

The extra costs are the proxy class itself — generated once per entity type with ByteBuddy — and the fact that an initialising SELECT loads only that entity, whereas a find with an entity graph or a JPQL join fetch could have loaded the customer and its addresses in one statement.

There is also a subtle behavioural difference: a proxy that initialises after the transaction closed throws, whereas find would already have failed at the call site. So the rule is simple: reference for foreign keys, find or a fetch query for data.

Q6. "Why do entities need equals() and hashCode() that are safe before the id is assigned, and what is the standard implementation?"

Reveal answer

Strong answer An entity's identity is its database id, but the id is null while the entity is transient, and with IDENTITY generation it changes from null to a value during persist().

If hashCode() depends on the id, an entity placed in a HashSet before persist lands in one bucket, then after the id is assigned it belongs in another, and contains() returns false for an object the set holds — a broken set.

The standard implementation therefore has two parts. equals() returns true for the same reference, false when either id is null, and otherwise compares ids — so two unsaved objects are never equal, which is correct because they will become different rows.

hashCode() returns a constant, typically the class's hash, so an object's bucket never changes; the cost is that all entities of one class collide in a set, which is fine for the handful of entities a transaction holds.

Using every field for equality is the other common mistake: a managed entity would then change equality when you edit it, and Hibernate proxies would compare differently from real instances.

entity equals and hashCode, before and after the id existsruns offline
// BROKEN — the standard IDE-generated version.
@Entity
public class Order {
    @Id @GeneratedValue private Long id;
    @Override public boolean equals(Object o) {
        return o instanceof Order x && Objects.equals(id, x.id);
    }
    @Override public int hashCode() { return Objects.hash(id); }
}

var set = new HashSet<Order>();
Order o = new Order();
set.add(o);                 // id is null -> hashCode() = 31
em.persist(o);              // id assigned -> hashCode() CHANGES to 12345...
set.contains(o);            // FALSE. The object is in the wrong bucket. (See Q3 of E3.)

// This is the mutable-key problem, caused by the database rather than by a setter.

// FIX 1 — a CONSTANT hashCode, and equals on the id. Ugly, and correct.
@Override public int hashCode() { return getClass().hashCode(); }   // stable forever
@Override public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Order x)) return false;
    return id != null && id.equals(x.id);      // two transient entities are never equal
}
// A constant hash means a HashSet of orders degrades to a list -- acceptable,
// because entity sets are small; and it is what Hibernate's own docs recommend.

// FIX 2 — a BUSINESS KEY assigned at construction. The better design.
@Entity
public class Order {
    @Id @GeneratedValue private Long id;
    @NaturalId private final String orderNumber = "ORD-" + UUID.randomUUID();
    @Override public boolean equals(Object o) {
        return o instanceof Order x && orderNumber.equals(x.orderNumber);
    }
    @Override public int hashCode() { return orderNumber.hashCode(); }
}
// Stable from construction, never changes, and meaningful to the domain.

// NOTE the proxy problem: use `instanceof`, never getClass() == o.getClass(),
// or an entity never equals its own Hibernate proxy.

The getClass() note is easy to miss and breaks silently. A proxy's class is a generated subclass, so an equals written with getClass() == o.getClass() reports that an entity is not equal to a lazily loaded reference to itself.

Land it Id-based equals with a constant hash is the only implementation that is stable across all four entity states.

Likely follow-ups
"If hashCode is a constant, does that not make a HashSet of entities O(n)?"

Yes, every element lands in one bucket, and lookup degrades to a linear scan. Since Java 8, a bucket with more than eight entries becomes a red-black tree, but only when the elements are Comparable, which entities usually are not, so it stays a linked list.

In practice the sets involved are an aggregate's collections — tens or hundreds of children — and a scan of two hundred elements is microseconds, far below the cost of a single SQL statement.

Where it would hurt is a set of a hundred thousand entities in a batch job, and there the answer is to key a HashMap by id explicitly rather than to make the entity's hash unstable.

I would rather be slow and correct than fast and lose elements.

"What about using a natural key or a client-generated UUID in equals instead?"

Both are good when they exist.

A UUID assigned in the constructor is stable from the first line of the object's life, so equals and hashCode can use it in the normal way, buckets never move, and the constant-hash workaround is unnecessary — this is one of the quiet advantages of client-generated ids.

A natural key such as an ISBN works the same way as long as it is immutable and set at construction; Hibernate's @NaturalId makes that explicit.

What I avoid is a natural key that can change, such as an email, because an object that changes its hash while inside a set is lost. And I still compare through getters, so that a proxy on the other side of the comparison initialises correctly.

"Can you use Lombok's @Data or a Java record for an entity?"

Not for the entity class. @Data generates equals and hashCode over every field, which changes as you edit the entity and, for bidirectional relationships, recurses through the parent and child collections until it overflows the stack.

Records cannot be entities at all, because JPA requires a no-argument constructor and non-final fields that Hibernate can set through reflection or bytecode.

What records are good for, as of Aug 2026, is @Embeddable types — Hibernate 6.2 added record support for embeddables and Jakarta Persistence 3.2 standardised it — and for projections and DTOs.

If Lombok is used, @Getter @Setter plus a hand-written id-based equals is the safe combination, and @ToString must exclude the associations.

"How does this interact with Hibernate's PersistentSet on the inverse side?"

Hibernate's PersistentSet is a wrapper around a HashSet that it fills at load time, calling hashCode on each child as it adds it.

If the hash depends on the id, that is fine at load because ids exist, but consider order.getLines().add(newLine) followed by persist with IDENTITY generation: the line entered the set with a null-id hash, then got an id, and order.getLines().remove(line) now searches the wrong bucket and returns false, so orphan removal never fires and the row survives.

With a constant hash, add and remove both find the element. The proof is a two-line test with a HashSet, an entity, and a setId call in between.

Q7 · Scenario. "A service loads an entity, calls em.remove(entity), then later in the same transaction calls em.persist(entity) on the same object after the user changes their mind. What happens at commit?"

Reveal answer

Strong answer Nothing is deleted. remove() moves a managed entity to the removed state and queues a DELETE, but the row is still there until flush.

Calling persist() on a removed entity is explicitly defined by JPA to cancel the removal and return the entity to managed — Hibernate un-schedules the DELETE. At commit the dirty check runs as normal, so if the entity's fields changed in between, an UPDATE goes out; otherwise no SQL runs for that entity at all.

The evidence to check if the team is confused: enable org.hibernate.SQL and confirm no DELETE appears.

Where this bites is the opposite order — persist() then remove() in one transaction cancels the INSERT, so the entity never touches the database, and code that expected an id to be reserved sees the id assigned (from the sequence) but no row.

And if a different object with the same id is persisted after the remove, Hibernate must flush the DELETE first or the INSERT hits a primary-key conflict; it handles that ordering only if you flush() between the two.

Land it Remove and persist are queue operations until flush, and JPA defines persist-after-remove as "never mind".

Likely follow-ups
"What if the persist() after remove() happens in a different transaction?"

Then the DELETE was already flushed and committed by the first transaction, and the object is detached with its old id.

Calling persist() on it in the second transaction throws PersistentObjectException: detached entity passed to persist for a generated id, because Hibernate sees an id on an object it does not manage.

merge() would SELECT, find no row, treat the object as new and insert it — but with a freshly generated id, not the old one, so any references to the old id are dangling.

If the business genuinely needs "undo delete", the honest design is soft delete with a restore method, or a proper copy constructor that creates a new transient object. Resurrecting a deleted entity object across transactions is a smell.

"How would you make 'delete row then insert a replacement with the same unique key' work in one transaction?"

The problem is flush ordering: inserts run before deletes, so the INSERT collides with the not-yet-deleted row on the unique constraint. Three options. Call em.flush() between the remove and the persist, which forces the DELETE out first; this is the cleanest fix.

Or avoid the delete entirely by loading the existing row and updating it in place, which is what most "replace" operations actually mean.

Or, on PostgreSQL, declare the unique constraint DEFERRABLE INITIALLY DEFERRED so it is checked at commit rather than per statement — that works but it moves the failure to commit time and MySQL does not support it.

I would take the flush and add a comment explaining why it is there.

"Does remove() on an entity cascade, and what happens to its children if the removal is cancelled?"

remove() cascades along CascadeType.REMOVE and ALL at the moment you call it, so every child in the collection is moved to the removed state and queued for DELETE.

A later persist() on the parent cascades along PERSIST, which also un-removes each child it reaches, so the whole graph is restored if the cascades are symmetrical.

If the parent has REMOVE but not PERSIST cascade, the children stay removed and are deleted at flush while the parent survives, which is a subtle way to lose data.

The safe way to think about it is that cascades are applied when the operation is called, not at flush, and the SQL log after the transaction is the only trustworthy proof.

"How would you verify in a test that no DELETE went out?"

I would run the sequence inside a TransactionTemplate in an integration test against Testcontainers PostgreSQL, then assert on two things. First, statistics: sessionFactory.getStatistics().getEntityDeleteCount() equals zero after commit. Second, the database: a JdbcTemplate count on the table in a separate connection, after commit, still returns the row.

I avoid asserting on the log text because log formats change. If the team uses hypersistence-utils, SQLStatementCountValidator.assertDeleteCount(0) is a one-liner that fails with the actual statements printed.

The important part is that the assertion runs after commit, not inside the transaction, because before flush nothing has happened either way.

Q8. "What is the snapshot Hibernate keeps for each managed entity, what does it cost, and which setting makes Hibernate skip it?"

Reveal answer

Strong answer When Hibernate loads an entity it stores, in the persistence context's entry for that object, an Object[] holding the value of every mapped field as loaded — the snapshot, or "loaded state".

At flush, dirty checking walks each managed entity and compares its current field values against that array, type by type; any difference marks the entity dirty and produces an UPDATE. The cost is memory and time proportional to the number of managed entities times their field count: each entity exists twice, and the flush is a full scan of the context, which is why a transaction holding 100,000 entities spends noticeable time in every flush — including the flushes triggered before each query.

Two things skip the snapshot. @Transactional(readOnly = true) makes Spring set the Hibernate session to read-only mode, where loaded entities carry no snapshot and are never dirty-checked. And Session.setDefaultReadOnly(true) or per-query setReadOnly(true) do the same for specific loads inside a writable transaction.

Bytecode enhancement with hibernate.enhancer.enableDirtyTracking replaces the comparison with tracked setters, but it is an opt-in build step most Spring teams do not use.

Land it Every read path that does not write should be readOnly — it halves memory per entity and removes the flush scan.

Likely follow-ups
"How does Hibernate compare the snapshot to the current state — is it equals() on each field?"

It is per-type comparison, not equals() on the entity.

For each attribute, Hibernate asks the attribute's JavaType whether the loaded value and the current value are equal — for BigDecimal that is compareTo semantics so scale does not matter, for byte arrays it is Arrays.equals, for embeddables it recurses into each component, and for associations it compares the identifiers.

Mutable types like Date and arrays are deep-copied into the snapshot so that in-place mutation is detected.

The cost is one comparison per attribute per managed entity per flush, which is why an entity with a large JSON document or a byte array compares slowly and why such columns are candidates for a separate lazily loaded entity.

"What does bytecode enhancement actually change, and would you turn it on?"

The Hibernate enhancer plugin, for Maven or Gradle, rewrites the entity classes at build time. With enableDirtyTracking, every setter records the attribute name in a small tracker inside the entity, so at flush Hibernate asks "which attributes changed?

" instead of comparing the whole snapshot, turning the flush from proportional to entities times attributes into proportional to entities actually modified.

With enableLazyInitialization it also makes individual basic attributes and to-one associations lazy without proxies, which is the only way to lazy-load a large column or the inverse side of a one-to-one. As of Aug 2026 Hibernate 7 has simplified the options to a single enhance switch.

I would turn it on in a service with very wide entities or huge contexts, after running the full test suite, because field access and inheritance edge cases occasionally behave differently.

"Can you mark a single entity read-only inside a writable transaction?"

Yes, at three levels. session.setReadOnly(entity, true) on an already-loaded entity drops its snapshot and excludes it from dirty checking, and you can flip it back. A query hint, query.setHint(HibernateHints.HINT_READ_ONLY, true) or Spring Data's @QueryHints(@QueryHint(name = "org.hibernate.readOnly", value = "true")), loads everything that query returns without snapshots.

And @Immutable on the entity class makes every instance read-only always, with updates silently ignored or, since Hibernate 6.2, rejected depending on the setting.

The common pattern is a writable transaction that loads a handful of reference entities read-only through the hint and one aggregate normally, so the flush scan covers only what can change.

"How would you measure how much time a flush spends dirty-checking in production?"

With statistics on, Statistics.getFlushCount() and getEntityUpdateCount() tell me how often and how much, and Hibernate's org.hibernate.stat logger at DEBUG prints per-session summaries. For time, I would wrap the transactional method in a Micrometer timer and correlate with the number of managed entities, or use the Hibernate 6 session event listener hibernate.session.events.auto with a custom BaseSessionEventListener that overrides flushStart and flushEnd. A JFR recording or an async-profiler flame graph will show DefaultFlushEntityEventListener.dirtyCheck at the top when the context is too big; that frame appearing at all is the diagnosis, and the fix is either readOnly, clear(), or a smaller transaction.

Drill · Flush & dirty checking

This group tests whether you can predict the exact moment a statement leaves the JVM, and why Hibernate chose that moment.

Q9. "List every event that triggers a flush under FlushModeType.AUTO, and explain the reasoning behind the query-triggered one."

Reveal answer

Strong answer Under AUTO, Hibernate flushes on four events. One: transaction commit, so that pending changes are written before the JDBC commit.

Two: before executing a JPQL, HQL or criteria query whose target tables overlap with entities that have pending changes — Hibernate checks the query's entity types against the action queue and flushes only if they intersect, so a query on products does not flush a dirty order.

Three: before any native SQL query, always, because Hibernate does not parse your SQL and cannot tell what tables it touches — unless you tell it with addSynchronizedEntityClass on the native query. Four: an explicit flush().

The reasoning behind the query-triggered flush is read-your-own-writes consistency: if you persisted an order and then ran select count(o) from Order o, returning a count that excludes the order you just created would violate the expectation that a transaction sees its own changes.

The database can only include the row if the INSERT has been sent. FlushModeType.COMMIT disables events two and three and accepts stale query results in exchange for fewer flushes — a legitimate choice for read-mostly transactions.

Going deeper One detail worth knowing is that the native-query rule is a JPA-compliance behaviour. When Hibernate is bootstrapped through JPA — which Spring Boot always does — FlushModeType.AUTO flushes before every native query.

When the legacy Session API is used with Hibernate's own FlushMode.AUTO, a native query does not trigger a flush unless you declare the tables it touches with addSynchronizedQuerySpace or addSynchronizedEntityClass.

The switch is hibernate.flushMode together with the JPA compliance settings, and it explains why a team migrating old Session-based code into a Spring Boot service suddenly sees flushes before every native query.

The overlap check for JPQL is done on "query spaces" — the set of table names each entity maps to — and it is conservative: a query touching a table that any dirty entity maps to triggers a full flush of the whole action queue, not only the overlapping entities.

The way to see it happening is logging.level.org.hibernate.event.internal.AbstractFlushingEventListener=DEBUG, which logs "Flushing session" with counts, or Statistics.getFlushCount() before and after the query.

Land it AUTO flush is Hibernate keeping "you see your own writes" true; native queries pay the full price because Hibernate cannot see inside them.

Likely follow-ups
"When would you deliberately set FlushModeType.COMMIT, and what is the risk?"

I would set it on a transaction that does many reads and a few writes where the reads never need to see the pending writes — a report that also records "last run at", or an import that queries lookup tables between inserts.

It removes the overlap check and every mid-transaction flush, so the work goes out as one batch at commit, which pairs well with hibernate.jdbc.batch_size.

The risk is stale reads: a JPQL count run after a persist returns the old count, and a query that should find the entity you just created returns nothing, which produces "works in the test, fails with duplicates in production" bugs.

I scope it per query with query.setFlushMode(COMMIT) rather than per session, so the exception is explicit and reviewable.

"Does a Spring Data derived query like findByStatus trigger the flush too?"

Yes. Derived queries are turned into JPQL — or, in Spring Data 3 and 4, directly into Hibernate's criteria or SQM tree — so they are entity queries with known query spaces, and the overlap check applies.

If the persistence context holds a dirty Order and you call orderRepository.findByStatus(PAID), Hibernate flushes the order first and the query sees it. If you call productRepository.findBySku(), the spaces do not overlap, and no flush happens.

Native @Query(nativeQuery = true) methods flush unconditionally; there is no Spring Data annotation for synchronised spaces, so a custom repository fragment unwrapping NativeQuery is the way to narrow it. The behaviour is visible in the SQL log as the UPDATE preceding the SELECT.

"Why does Hibernate flush the whole action queue and not just the overlapping entities?"

Because the action queue has a fixed execution order — inserts, updates, collection changes, deletes — and partial flushing would have to reason about foreign-key dependencies between the entities it flushes and the ones it leaves behind.

Flushing an order line's INSERT without the parent order's INSERT would violate the constraint, and tracking those dependencies per flush would cost more than the flush itself. So the rule is simple: if any dirty entity's tables overlap with the query, everything pending goes out.

The practical consequence is that the "cost" of a mid-transaction query is the size of the whole pending change set, which is another argument for small transactions and for keeping bulk work in a flush-and-clear loop rather than mixing it with queries.

"Is the commit-time flush guaranteed even if my method never touched a query?"

Yes, as long as the transaction commits. JpaTransactionManager.doCommit calls EntityTransaction.commit(), and Hibernate's commit always runs a flush first unless the flush mode is MANUAL, which is what readOnly = true sets.

The exceptions are rollback, where nothing is flushed; a transaction marked rollback-only by an inner REQUIRED method that threw, which ends in UnexpectedRollbackException; and code running outside any transaction, where the EntityManager is closed without a commit and the changes are simply discarded — that is the most common case of "my persist did nothing". A quick check is TransactionSynchronizationManager.isActualTransactionActive() at the point of the change.

Q10 · Scenario. "A batch job's flushes get slower as the job runs: the first flush takes 5 ms, the thousandth takes 900 ms, even though each flush writes the same 50 rows. Diagnose."

Reveal answer

Strong answer Symptom: flush time grows linearly with job progress while the work per flush is constant. Evidence: enable hibernate.generate_statistics and log getFlushCount() and getEntityCount() per iteration, and take a heap histogram — you will see the number of managed entities climbing by 50 per flush.

Cause, ranked first by a wide margin: the job calls flush() but never clear(), so every entity ever persisted stays managed, and each flush dirty-checks the entire context — 50,000 entities on the thousandth flush, each compared against its snapshot.

The second candidate is a query in the loop triggering AUTO flushes on top of the explicit ones, doubling the scans.

Fix: call em.clear() immediately after each flush() so the context stays at batch size, or move the job to a StatelessSession, which has no context to scan.

Prevention: a metric on persistence-context size in batch jobs, and a code review rule that a flush() in a loop is always paired with clear().

why the thousandth flush is slower than the firstruns offline
// The persistence context accumulates every entity it has seen. Dirty checking
// walks ALL of them on EVERY flush and compares each field to its snapshot.
//
//   flush 1:      1 entity  compared   -> fast
//   flush 1000:   1000 entities compared -> 1000x the work
//
// Total work across the job is O(n^2). The job starts fast and degrades, which
// is the signature of this bug rather than of a slow database.

// BROKEN
@Transactional
public void importAll(List<Row> rows) {
    for (Row r : rows) {
        em.persist(toEntity(r));      // nothing is ever released
    }
}

// FIXED — flush and clear in batches.
@Transactional
public void importAll(List<Row> rows) {
    for (int i = 0; i < rows.size(); i++) {
        em.persist(toEntity(rows.get(i)));
        if (i % 50 == 0) {            // must match hibernate.jdbc.batch_size
            em.flush();               // send the batch to the database
            em.clear();               // and DETACH everything, freeing the snapshots
        }
    }
}

// Also worth knowing:
//  - readOnly = true sets FlushMode.MANUAL, so no dirty checking runs at all.
//    For a read-only pass over many rows, that alone removes the problem.
//  - For a pure bulk load with no entity semantics needed, JdbcTemplate
//    batchUpdate will beat any JPA configuration and hold nothing.

The quadratic shape is the diagnostic. A job that is slow from the first row is usually a slow query; a job that starts fast and gets progressively slower is almost always an unbounded persistence context.

Land it Flush cost is proportional to the context size, not the change size — clear after every flush or the job is quadratic.

Likely follow-ups
"The team added clear() after every flush and the job is still slow. What next?"

Then the context is not the bottleneck any more and I look at the statements. Is JDBC batching actually on — hibernate.jdbc.batch_size=50 plus order_inserts=true and order_updates=true — and are the ids IDENTITY, which disables insert batching entirely?

Is each row triggering a SELECT because save() is taking the merge branch on an assigned id, or because a @ManyToOne is being resolved with findById per row instead of getReferenceById? Is a query inside the loop causing an AUTO flush before every iteration?

And on the database side, are there triggers or a missing index on a foreign key that makes each INSERT slow? The evidence is the statement count per chunk from statistics: fifty rows should be one batched INSERT, not fifty statements plus fifty SELECTs.

"Why not just use a StatelessSession for the whole job?"

Often that is the right answer. A StatelessSession has no persistence context, no dirty checking, no cascades and no first-level cache: insert(), update() and delete() map directly to statements, and since Hibernate 6 they honour JDBC batching, with Hibernate 7 adding upsert() and multi-row insertMultiple().

Memory stays flat regardless of row count. What you lose is everything the context gives you: no lazy loading beyond fetch(), no lifecycle callbacks, no Envers auditing, no automatic collection handling, and no optimistic locking unless you carry the version yourself.

So I use it for import and export jobs where the rows are independent, and keep the flush-and-clear loop for jobs that build object graphs or need the callbacks.

"What batch size would you pick, and why not 5,000?"

Between twenty and a hundred, and I would measure. The gain from batching is fewer round trips; going from one to fifty cuts them by fifty times, going from fifty to five thousand cuts the remaining two percent, which is not worth the cost.

That cost is memory — five thousand managed entities and their snapshots per chunk — plus a transaction and a JDBC batch that are large enough to hit driver and server limits, such as PostgreSQL's parameter limit of 65,535 per statement when multi-row inserts are rewritten.

A chunk of fifty also keeps each transaction short, so a failure loses fifty rows of work rather than five thousand and the row locks are held briefly. Spring Batch's default chunk sizes sit in the same range for the same reasons.

"How does this look if the job runs under Spring Batch?"

Spring Batch's chunk-oriented step does the flush-and-clear discipline for you when you use JpaItemWriter: each chunk commits its own transaction, the writer calls flush() and the step's transaction ends, so the EntityManager is closed and the context is dropped between chunks.

JpaItemWriter calls merge per item by default, which means a SELECT per row for entities with assigned ids; setting usePersist(true) avoids that for new rows.

On the read side, JpaPagingItemReader issues a fresh query per page in its own transaction, while JpaCursorItemReader streams through a single transaction. The chunk size property is the batch size, and hibernate.jdbc.batch_size should match it.

Q11. "By default Hibernate's UPDATE sets every column, even the ones you did not change. Why, and when would you turn on @DynamicUpdate?"

Reveal answer

Strong answer Hibernate generates one UPDATE statement template per entity at startup — update orders set customer_id=?, status=?, total_amount=?, ... where id=? and version=? — and reuses it for every update of that entity.

Because the SQL text never changes, the JDBC driver and the database can cache the prepared statement and its execution plan, and JDBC batching can group updates of different rows into one batch, which requires identical SQL. Writing unchanged columns with their existing values costs a few bytes on the wire and nothing in the database.

@DynamicUpdate generates a statement containing only the changed columns, which means a different SQL text for every combination of changed fields: no statement cache hits, and updates that cannot be batched together.

It is worth it in two cases: entities with very wide rows or large text and binary columns where writing them back costs real I/O, and tables where two transactions routinely update disjoint columns of the same row and you want the database's row lock to be the only conflict, though optimistic locking still fires on the version column either way.

Land it Full-column updates are a statement-cache and batching decision; reach for @DynamicUpdate only for wide rows, and measure.

Likely follow-ups
"Does writing unchanged columns really cost nothing in the database?"

Almost nothing, with two exceptions.

On PostgreSQL every UPDATE writes a whole new row version regardless of which columns changed, so the set of columns in the SET clause does not change the write amplification — but if an indexed column is in the SET list with the same value, PostgreSQL still applies its heap-only-tuple optimisation, because it compares values, not the statement text.

The first exception is TOAST: a large text or bytea column that is rewritten with the same value can force re-toasting on some paths.

The second is MySQL replication and triggers: row-based binlog events carry the full before and after images either way, but a BEFORE UPDATE trigger fires for the row even when nothing changed.

So the real costs are on the Hibernate side — statement caching and batching — not in the storage engine.

"How does @DynamicUpdate interact with optimistic locking?"

The version check still works, because the generated UPDATE always includes version = ? in the SET and and version = ? in the WHERE, whatever subset of columns changed.

What changes is the meaning of a conflict: two transactions updating disjoint columns of the same row still conflict, because both bump the same version.

If you want disjoint-column updates to succeed, you need @OptimisticLocking(type = OptimisticLockType.DIRTY), which requires @DynamicUpdate and puts only the changed columns' old values in the WHERE clause instead of a version — then a title edit and a status edit both commit.

The trade-off is that detached edits across transactions are no longer protected unless the client carries the old values, which is why I use it rarely and deliberately.

"How would you verify the statement-cache claim on a real driver?"

On PostgreSQL, pgjdbc's server-side prepared statements kick in after prepareThreshold executions, five by default, of the same SQL text on the same connection; with @DynamicUpdate each distinct column combination is a different text and may never reach the threshold.

I would confirm with pg_stat_statements: full-column updates show as one normalised entry with a high call count, dynamic updates as many entries with low counts.

On MySQL, cachePrepStmts=true with prepStmtCacheSize on the Connector/J URL is per-connection, and the Com_stmt_prepare status counter rising with the update count shows cache misses. With Hikari the cache is the driver's, not the pool's, so the same test applies per connection.

"What about @DynamicInsert — same reasoning?"

Same mechanics, different motivation. @DynamicInsert omits columns whose value is null from the INSERT, which lets database defaults such as created_at DEFAULT now() or status DEFAULT 'NEW' apply, because Hibernate would otherwise write an explicit NULL. The cost is the same statement-text variability, and for inserts it also breaks JDBC batching of entities with different null patterns. My preference is to set the defaults in Java, in the field initialiser or the constructor, so the INSERT is fixed and the object has the value before flush; where the database must own the value, @Generated on the field tells Hibernate to exclude the column and read it back, which is narrower than making the whole INSERT dynamic.

Q12. "In what order does Hibernate execute the statements in a flush, and why does that order matter for foreign keys?"

Reveal answer

Strong answer Hibernate drains the action queue in a fixed order: entity inserts first, then entity updates, then collection removals, then collection element updates and inserts, then entity deletes — and inside each group, in the order the operations were queued, unless order_inserts or order_updates regroups them by entity type.

Inserts go first so that a new parent row exists before a child referencing it is inserted, and Hibernate orders inserts by dependency where a cascade from parent to child makes that visible.

Deletes go last so that a child pointing at a parent is gone before the parent row is removed. The order is why two patterns cause constraint violations.

Deleting a row and inserting a replacement with the same unique key in one transaction fails, because the INSERT runs before the DELETE — you must flush() between them.

And a unidirectional @OneToMany with @JoinColumn inserts the child with a null foreign key first and then issues an extra UPDATE to set it, which fails if the column is NOT NULL, unless nullable = false is set on the @JoinColumn so Hibernate includes the key in the INSERT.

Land it Inserts, updates, collections, deletes — and when your code needs a different order, an explicit flush is the honest fix.

Likely follow-ups
"What do hibernate.order_inserts and order_updates change, and why are they off by default?"

They regroup the action queue by entity type before execution: with order_inserts=true, all Order INSERTs are sent together, then all OrderLine INSERTs, instead of the interleaved order in which your code persisted them.

That is what makes JDBC batching work in a loop that persists a parent and its children alternately, because a batch must contain identical SQL. Hibernate still respects parent-before-child dependencies while sorting.

They are off by default because reordering changes observable behaviour — trigger firing order, and the exact statement that fails on a constraint violation — and because sorting has a small cost per flush.

In a service with batch_size set, I always turn both on, along with batch_versioned_data.

"Where does a cascade delete of a collection sit in that order, and can it violate a foreign key?"

Entity deletes are the last group, and inside it Hibernate orders children before parents when the cascade made the relationship visible, so an order's lines are deleted before the order.

It goes wrong when the dependency is not visible to Hibernate: a child that references the parent only through a foreign key with no mapped association, or a many-to-one from an unrelated table. Then the parent DELETE can run first and the database rejects it.

The fixes are to map the association so Hibernate can order it, to declare ON DELETE CASCADE in the schema with @OnDelete on the mapping, or to call flush() after removing the children explicitly.

The deadlock case in Q68 is the same ordering rule seen from the lock's point of view.

"How would you see the exact order Hibernate chose for a given transaction?"

logging.level.org.hibernate.SQL=DEBUG prints statements in execution order, and logging.level.org.hibernate.orm.jdbc.bind=TRACE prints the bound parameters so you can match rows. For batching you need org.hibernate.engine.jdbc.batch=DEBUG in Hibernate 6 and 7, which logs "Executing batch" with sizes, because the SQL logger prints each statement once even when it is batched.

For a pure Java view, Statistics gives counts but not order.

In an integration test, a datasource proxy such as datasource-proxy or p6spy captures the real JDBC calls, which is the only way to prove batching happened, since Hibernate's own log shows the logical statements rather than what the driver sent.

"Does the order change with IDENTITY ids?"

Yes, for inserts. With IDENTITY the INSERT of each entity runs immediately inside persist(), not at flush, so inserts happen in your code's call order and cannot be reordered or batched — they are effectively before everything else in the queue.

Updates and deletes of those entities still queue normally. That interleaving is why a method that persists a child before its parent works with SEQUENCE, where the flush sorts them, but fails with IDENTITY, where the child INSERT runs at once with a null foreign key.

The same difference shows up in @PostPersist, which fires at persist time for IDENTITY and at flush time for SEQUENCE.

Q13 · Scenario. "A method persists an order, then runs a native SQL query on a completely unrelated audit table. The SQL log shows the order INSERT before the audit query. A colleague says that's a bug. Is it?"

Reveal answer

Strong answer It is not a bug; it is the native-query rule. Hibernate flushes before every native SQL query in AUTO mode because it cannot parse the SQL to know which tables it touches, so it takes the safe path and writes everything pending.

The evidence is exactly the log the colleague saw: the INSERT immediately precedes the native query, even though the query does not need it.

The consequence is only a cost: an earlier flush than necessary, which in a loop of native queries can mean a flush per iteration. There are three fixes if that cost matters.

Tell Hibernate what the query touches — query.unwrap(NativeQuery.class).addSynchronizedEntityClass(AuditRow.class) — so the overlap check runs and the order INSERT stays queued. Or express the audit query in JPQL, where Hibernate sees the tables.

Or set FlushModeType.COMMIT on that query with setFlushMode, accepting that it will not see pending changes. Prevention is a rule of thumb: native queries in write transactions get a synchronized-entity declaration, always.

Land it Native SQL is opaque to Hibernate, so it flushes defensively — you can narrow that with addSynchronizedEntityClass.

Likely follow-ups
"They added addSynchronizedEntityClass and now the audit query is missing a row it should see. What happened?"

They declared the wrong table set. addSynchronizedEntityClass(AuditRow.class) tells Hibernate the native query reads only the audit table, so it flushes only if an AuditRow is dirty.

If the native query actually joins orders — say it reads the order's status to filter — then the pending order INSERT stays queued and the query misses it.

The fix is to list every entity whose table the SQL touches, or use addSynchronizedQuerySpace("orders") with table names. The check is the SQL log: the INSERT should now appear before the query again.

This is why I treat synchronised spaces as a documented contract on the query, and why a native query that needs pending writes is often better as JPQL.

"What is the actual cost of the extra flush if there are no pending changes?"

A flush with an empty action queue still walks every managed entity and compares it against its snapshot to look for dirty ones, so the cost is proportional to context size, not to the number of changes.

With ten entities managed it is microseconds; with fifty thousand it is hundreds of milliseconds per native query. That is the scenario where a loop of native queries in a batch job becomes quadratic.

The measurement is Statistics.getFlushCount() against the number of queries, and the fix is the synchronised space, FlushModeType.COMMIT on the query, or keeping the context small with clear(). If the context is already tiny, the extra flush is not worth the code change.

"Would a JPQL query on the audit entity have flushed the order?"

No. A JPQL query on AuditRow has the query space {audit_row}, and the pending action is an INSERT on orders; the spaces do not intersect, so Hibernate skips the flush.

That is precisely the argument for expressing the audit read in JPQL or the criteria API where possible: Hibernate can see the tables and make the narrow decision automatically, with no per-query declaration to keep correct.

Where the audit read needs SQL that JPQL cannot express — a window function, a lateral join — Hibernate 6.6 and 7 have closed much of that gap in HQL, so the native query is rarer than it used to be as of Aug 2026.

"Is an early flush ever harmful beyond cost?"

It can change which statement fails and when. A flush inside the method surfaces a constraint violation at the query line rather than at commit, which sometimes hides behind a catch block that was written for the query.

It also means the row is written earlier, so a row lock is held for longer — from the flush to commit instead of from commit to commit — which slightly widens the window for lock waits on hot rows.

And with REQUIRES_NEW nesting, an early flush in the outer transaction can make its uncommitted row visible to itself but still invisible to the inner one, leading to confusing "phantom" behaviour. None of these are bugs; they are reasons to know when flushes happen.

Drill · Sessions & transactions in Spring

This group tests whether you know that "no transaction" means "no persistence context", and what that does to every line after the repository call.

Q14. "In a Spring Boot service, who creates the EntityManager, when, and when does it close?"

Reveal answer

Strong answer With open-session-in-view off, the JpaTransactionManager creates it.

When a call crosses a @Transactional boundary, the transaction interceptor asks the manager to begin; the manager creates an EntityManager from the factory, binds it to the current thread in TransactionSynchronizationManager, and starts a JDBC transaction on a pooled connection when the first statement needs one.

The EntityManager you inject with @PersistenceContext is a shared proxy that looks up the thread-bound instance on every call, which is why one field can be safely used by all threads.

Nested @Transactional calls with the default REQUIRED propagation join the same transaction and therefore the same persistence context. When the outermost method returns, the manager commits — flush, then JDBC commit — and closes the EntityManager, detaching everything.

A repository call outside any transaction gets a persistence context that lives only for that one call, because SimpleJpaRepository is itself @Transactional. With open-session-in-view on, an OpenEntityManagerInViewInterceptor creates the context at the start of the HTTP request instead, and transactions inside the request reuse it.

Going deeper The proxy detail is worth being precise about. Spring injects a SharedEntityManagerCreator proxy for @PersistenceContext and for a plain EntityManager field; on each method call it looks up an EntityManagerHolder bound to the current thread in TransactionSynchronizationManager.

If a transaction is active it delegates to that EntityManager; if none is active, it creates a new one for the single call and closes it afterwards, which is why em.find() outside a transaction returns a detached entity and em.persist() outside one throws TransactionRequiredException.

Repository beans are @Transactional(readOnly = true) at the class level, with the mutating methods overridden as read-write, which is the "one tiny transaction per repository call" behaviour.

As of Aug 2026, Jakarta Persistence 3.2 also gives EntityManagerFactory.runInTransaction(em -> ...) and callInTransaction for code outside Spring's proxies, and Spring's TransactionTemplate remains the programmatic option inside them. Verification is a log line: logging.level.org.springframework.orm.jpa=DEBUG prints "Opened new EntityManager" and "Closing JPA EntityManager" around each transaction.

Land it The transaction manager owns the session's lifetime; your service method's boundary is the session's boundary.

Likely follow-ups
"When exactly is the JDBC connection borrowed from Hikari, and when is it returned?"

By default, at transaction begin: JpaTransactionManager.doBegin calls EntityTransaction.begin(), and Hibernate's LogicalConnectionManagedImpl acquires a connection immediately so it can call setAutoCommit(false). It is returned after commit or rollback, when the EntityManager closes.

With hibernate.connection.provider_disables_autocommit=true and Hikari's auto-commit=false, acquisition moves to the first statement, which is the Q36 fix.

Spring adds one more wrinkle: if the transaction is readOnly, Spring itself may fetch the connection early to call setReadOnly(true), and in Spring 6.1+ the JPA dialect passes the flag to Hibernate instead.

The simple test is Hikari's active gauge during a sleep placed before the first repository call.

"What happens if a service method with REQUIRED is called from a thread with no transaction, on a virtual thread?"

Nothing special: a new transaction begins, and the EntityManager is bound to the current thread through a ThreadLocal, which virtual threads support. The difference is scale.

Virtual threads are cheap, so a service that used to be limited to two hundred platform threads can now have ten thousand concurrent requests each wanting a pooled connection, and Hikari becomes the bottleneck — pending threads climb and the pool-timeout errors appear.

The other historical concern was pinning: a virtual thread blocked inside a synchronized block, which old JDBC drivers used, pinned its carrier. As of Aug 2026, with JDK 24's JEP 491 that pinning is gone, and pgjdbc and Connector/J had already removed most synchronised sections.

So the design rule becomes "size the pool for the database, not for the thread count".

"Can two EntityManagers exist on one thread at the same time?"

Yes, with REQUIRES_NEW or NOT_SUPPORTED propagation. Spring suspends the outer transaction's resources — unbinds its EntityManagerHolder and connection — and binds a new EntityManager on a second pooled connection for the inner call.

The shared proxy resolves to whichever is bound at the moment, so the same injected field talks to the inner context during the inner call and the outer context after it resumes.

Two contexts means two identity maps, two connections and two flushes, with the failure modes from Q17.

The other way is a hand-created EntityManagerFactory.createEntityManager(), which is unmanaged and must be closed by you; I only do that in tests or in a batch reader that needs its own lifecycle.

"How does @Transactional on the repository interact with @Transactional on the service?"

They compose through propagation. The service method's REQUIRED transaction starts first; the repository's own @Transactional sees an existing transaction and joins it, so there is one EntityManager and one commit.

Because the repository class is readOnly = true by default and the service is read-write, the repository's flag does not downgrade the transaction — Spring keeps the outer definition, and only warns if you try to join a read-only transaction with a read-write inner one.

Without a service transaction the repository's own boundary is the whole unit of work, which is what makes lazy loads after the call fail. So the repository annotation is a fallback, and the design intent is that services own the boundary.

Q15 · Scenario. "A LazyInitializationException appears only in production, never in local dev or in the integration tests. Diagnose in order."

Reveal answer

The real test Whether you look for the environment difference that changes the session's lifetime, rather than sprinkling @Transactional.

Strong answer Symptom: could not initialize proxy - no Session in production only.

Evidence: compare the effective spring.jpa.open-in-view value per environment (Boot prints a warning at startup when it is unset; a production profile may set it false), check whether the failing call runs on a different thread in production — @Async, a message listener, a virtual-thread executor, a scheduled job — and check whether the integration tests are annotated @Transactional, which wraps each test in one transaction and hides every lazy-load problem.

Ranked causes: one, OSIV is on locally and off in production, so lazy fields touched in the controller or serialiser work locally and fail in prod; two, the tests run inside a test transaction that keeps the session open, so the code path is never exercised detached; three, production serialises an entity to JSON in a path — an exception handler, an audit hook — that dev never hits.

Fix: load what the response needs inside the service transaction with a join fetch or a projection, and return a DTO. Prevention: set open-in-view: false in every environment including tests, and remove @Transactional from tests that exercise the web layer.

Land it The exception is not the bug — it is the environment that hides it locally that you must remove.

Likely follow-ups
"You turned OSIV off in every environment and the exception now appears in dev too. Good — but what is the fastest safe fix for the failing endpoint?"

The fastest safe fix is to load what the endpoint returns inside the service transaction: add a repository method with @EntityGraph(attributePaths = {"lines", "customer"}) or a JPQL join fetch, and map the result to a response record before returning.

That is a fifteen-minute change with no behavioural risk. What I would not do is put @Transactional on the controller, which is OSIV by another name, or switch the collection to FetchType.EAGER, which makes every load of that entity pay for the collection forever.

If the response needs a large collection paginated, the honest fix is a second endpoint. As of Aug 2026 Spring Boot still logs the OSIV warning at startup precisely so teams make this decision explicitly.

"How do you write an integration test that would have caught this?"

The test must not be @Transactional and must go through the web layer.

With @SpringBootTest(webEnvironment = RANDOM_PORT) and a TestRestTemplate or WebTestClient call, the request runs on a Tomcat thread with the real filter chain and the real OSIV setting, so the serialiser touches the entity after the service transaction ended, exactly as in production.

Setting spring.jpa.open-in-view=false in the test profile makes it strict. I also add a query-count assertion around the call so an accidental fix by eager loading shows up as extra statements.

Tests that use MockMvc with @WebMvcTest mock the service, so they cannot catch it, and @DataJpaTest is transactional by default, which hides it.

"Why did the test transaction hide it, mechanically?"

A @Transactional test wraps the whole test method in one transaction that Spring rolls back at the end. Every service call inside joins it with REQUIRED, so the EntityManager stays open for the entire test and every lazy proxy can still load.

Nothing is ever detached, no commit runs, and even flush ordering bugs can hide because the rollback discards the queue — though Hibernate does flush before JPQL queries, so some show.

The test also passes objects between calls in the same identity map, so identity-based assertions succeed that would fail across real transactions. That is why I keep test transactions only for repository-level tests and run service and web tests with committed transactions and Testcontainers.

"Is there a way to make LazyInitializationException impossible rather than just caught earlier?"

Two settings change the failure mode, and neither is a real fix.

hibernate.enable_lazy_load_no_trans=true opens a temporary session per lazy access outside a transaction, which silently turns each access into a separate connection borrow and a separate read-committed snapshot — it hides N+1 and stale-data problems, and I would refuse it in review.

Spring's OSIV does the same at request scope.

The genuine way to make the exception impossible is architectural: entities never leave the service layer, every response is a DTO or projection built inside the transaction, and an ArchUnit rule enforces that controllers do not reference @Entity classes. Then a lazy proxy cannot escape because nothing carries it out.

Q16. "What exactly does @Transactional(readOnly = true) change in Hibernate, the JDBC connection, and the routing layer?"

Reveal answer

Strong answer Three layers change.

In Hibernate, Spring's HibernateJpaDialect sets the session's flush mode to MANUAL — no automatic flush at commit or before queries — and sets the session's default read-only flag, so entities loaded in that transaction carry no snapshot and are never dirty-checked, roughly halving memory per entity.

At the JDBC layer, Connection.setReadOnly(true) is called: PostgreSQL then rejects any write with an error, MySQL treats it as a hint and may use a lighter transaction mode, and Oracle ignores it.

At the routing layer, a AbstractRoutingDataSource or the AWS Advanced JDBC wrapper reads the same flag to send the transaction to a read replica — which means readOnly is also the switch that exposes you to replication lag, so a read-your-own-writes path must not be readOnly.

What it does not do: it is not enforcement — a native UPDATE on MySQL still runs — and it does not prevent the ORM from loading proxies or lazy collections. It is a performance and routing declaration, and every read path should carry it.

Land it readOnly means "no snapshots, no flush, and the driver and router may treat this as a replica-safe read" — which is a promise you must be able to keep.

Likely follow-ups
"A readOnly method is called from a read-write transaction. Which wins?"

The outer one. With REQUIRED propagation the inner call joins the existing transaction and Spring does not change its characteristics, so the session stays in AUTO flush mode with snapshots, and the connection stays read-write.

If the routing datasource decided replica-or-primary at the outer begin, the inner readOnly flag has no effect either.

The reverse — a read-write inner method joining a readOnly outer transaction — is the dangerous case: the inner writes are flushed only if something forces it, and on PostgreSQL the connection is read-only so the flush fails; Spring can catch it if validateExistingTransaction=true is set on the transaction manager, which throws IllegalTransactionStateException at the join. I set that flag in every service.

"How would you verify that readOnly transactions actually reach the replica?"

Two ways. On the application side, log the connection's target inside the transaction: with AbstractRoutingDataSource, log the lookup key from determineCurrentLookupKey(), and with the AWS Advanced JDBC Wrapper enable its readWriteSplitting plugin logging.

On the database side, run select pg_is_in_recovery() through a native query inside the readOnly method — it returns true on a replica — or check the replica's pg_stat_activity for the application name.

The subtle failure is ordering: Spring's LazyConnectionDataSourceProxy must wrap the routing datasource so the readOnly flag is known before the connection is fetched; if the physical connection is acquired at begin, before the flag is applied, every transaction goes to the primary and the replica sits idle.

"Does readOnly stop a native UPDATE or a bulk JPQL update?"

Not by itself. Flush mode MANUAL prevents dirty-checked UPDATEs, but a @Modifying JPQL statement or a native executeUpdate is sent directly to the connection.

On PostgreSQL, pgjdbc translates setReadOnly(true) into a READ ONLY transaction, so the database rejects the write with "cannot execute UPDATE in a read-only transaction".

On MySQL the driver sends START TRANSACTION READ ONLY only if readOnlyPropagatesToServer is true, which is the default in Connector/J 8, and then the server rejects writes; on Oracle and SQL Server nothing is enforced.

So the honest statement is: readOnly is enforced by the database when the driver propagates it, and never by Hibernate. Spring Data itself does refuse a @Modifying query in a readOnly transaction only if you configure it to.

"What about replication lag — how do you handle read-your-own-writes with readOnly routing?"

The write path and the immediate read after it must go to the primary.

The simplest rule is that any request that just wrote pins its reads to the primary: the write service returns the new state in the same transaction so the caller does not need to re-read, and endpoints that must read after a write are not readOnly.

For a stricter guarantee, PostgreSQL exposes the primary's pg_current_wal_lsn() after commit; the client carries it as a token, and a replica read first checks pg_last_wal_replay_lsn() >= token, waiting or falling back to the primary if not. The AWS wrapper and ProxySQL implement variants of that.

The design point is that readOnly is a routing hint, and the routing policy must know which reads are allowed to be stale.

Q17. "What is the difference between propagation REQUIRED and REQUIRES_NEW from the persistence context's point of view, and what goes wrong if the inner one modifies an entity the outer one holds?"

Reveal answer

Strong answer REQUIRED joins the caller's transaction and therefore shares its persistence context: the same identity map, the same action queue, one flush at the outer commit.

REQUIRES_NEW suspends the caller's transaction, opens a second one on a second JDBC connection with its own, empty persistence context, commits it independently, then resumes the outer. The two contexts do not know about each other.

So if the outer context holds order 17 as managed and the inner transaction loads order 17 too, it gets a separate object from a fresh SELECT, modifies and commits it.

When the outer transaction later flushes its own copy of order 17, one of two things happens: with @Version, the outer UPDATE fails with OptimisticLockException because the inner commit bumped the version; without it, the outer UPDATE silently overwrites the inner change with stale data.

The second cost is connections: REQUIRES_NEW holds two pool connections per thread, so ten nested calls under a pool of ten deadlocks the pool. Use it for audit rows or outbox entries that must survive the outer rollback, and never pass managed entities across the boundary.

Land it REQUIRES_NEW is a second session on a second connection — anything it shares with the outer one is shared by row, not by object.

Likely follow-ups
"The inner REQUIRES_NEW transaction updates a row the outer one has already flushed but not committed. What happens?"

A lock wait, and possibly a self-deadlock. The outer transaction holds a row lock from its flushed UPDATE on its own connection.

The inner transaction, on a second connection, tries to UPDATE the same row and blocks waiting for the outer to commit — which cannot happen, because the outer thread is blocked waiting for the inner call to return.

The database does not detect this as a deadlock because only one lock is involved; it looks like a single lock wait and lasts until innodb_lock_wait_timeout on MySQL, fifty seconds by default, or forever on PostgreSQL unless lock_timeout is set.

The thread dump shows the request thread inside the inner JDBC call. The fix is never to touch in the inner transaction any row the outer one may have written.

"When is REQUIRES_NEW the right tool, then?"

For a write that must survive the outer rollback and that touches only its own rows: an audit record of a failed attempt, a "job attempt" row incremented before risky work, an outbox row for a compensating event, or an idempotency-key reservation.

Each of those is a small INSERT on a table nobody else in the outer transaction writes. The pattern to avoid is "retry inside the same request", where the inner transaction re-reads data the outer holds.

I also check pool sizing: each nesting level holds a connection per thread, so a pool of ten with two levels supports five concurrent requests before the pool deadlocks.

Spring's NESTED propagation, which uses a JDBC savepoint on the same connection, is often what people actually wanted, but it is not supported by JpaTransactionManager with Hibernate.

"How do you carry data between the two contexts safely?"

By id, and by value. The inner method takes primitive arguments or a small record, loads its own entities by id in its own context, and returns ids or DTOs.

If the outer method needs to see the inner method's result — say the audit row's id — it receives the id and, if necessary, calls getReferenceById in its own context.

Passing a managed entity from the outer context into the inner method is the mistake: the inner context does not know it, so persist throws, merge copies it into a second managed object, and setting fields on it changes the outer object that will be flushed later with stale version data.

A code review rule that REQUIRES_NEW methods have no entity parameters is easy to enforce.

"What if the inner transaction commits and then the outer one rolls back — what does the user see?"

The inner write stays. That is the whole point when it is an audit row, and a data-integrity bug when it is anything else.

The classic example is an inner method that inserts a payment record with REQUIRES_NEW, then the outer order creation fails: the payment exists for an order that does not.

If the two must be atomic, they belong in one transaction; if they must be independent, the inner data must make sense on its own and reference the outer data by a nullable or soft reference.

I would also check exception handling: if the inner method throws, the outer transaction is not automatically marked rollback-only because the inner one was separate, so the outer method must decide explicitly whether to continue or propagate.

Q18 · Scenario. "Under load, requests wait 30 seconds for a connection and time out, but the database shows most sessions idle. The service has OSIV enabled and calls a payment gateway mid-request. Diagnose."

Reveal answer

Strong answer Symptom: pool exhaustion (HikariPool - Connection is not available, request timed out after 30000ms) with an idle database.

Evidence: Hikari's active and pending metrics, thread dumps showing request threads blocked in HttpClient calls to the gateway while holding a connection, and the gateway's latency graph.

Ranked causes: one, a @Transactional method that makes the gateway call inside the transaction, so each request holds a pooled connection for the gateway's full latency — at 2 seconds per call and ten connections, throughput caps at five requests per second; two, OSIV-driven lazy loads after the transaction re-borrow a connection while the response is rendered, extending the hold further; three, REQUIRES_NEW nesting doubling per-request connection use.

Fix, in order: move the remote call outside the transaction — load what you need, commit, call the gateway, then open a second short transaction to record the result; set open-in-view: false; set provider_disables_autocommit with Hikari auto-commit: false so connections are borrowed at first statement, not at transaction start.

Prevention: an alert on Hikari pending threads and a rule that no transaction contains network I/O.

Land it A connection held during a remote call is the pool's most expensive resource doing nothing — the transaction boundary must exclude I/O.

Likely follow-ups
"You moved the gateway call out of the transaction and the pool is still exhausting under load. What next?"

Then something else holds connections. I check three things in order. First, OSIV: with it on, the request thread keeps the EntityManager open, and any lazy load in the controller or serialiser borrows a connection again for the rest of the request; setting open-in-view=false closes that.

Second, the @Transactional boundary may still contain other slow work — a Kafka send().get(), a Redis call, a file upload — so I look at thread dumps for threads with a Hikari connection in their frames and no JDBC call on top.

Third, sizing: Hikari's maximumPoolSize of ten with a database that could handle fifty and p99 database time of 20 ms supports about 500 requests per second; above that the queue is arithmetic, not a bug, and the fix is a bigger pool or fewer statements.

"How do you size the pool, concretely?"

Start from the database, not the application.

A PostgreSQL primary is comfortable with roughly two to four active connections per core, so an 8-core instance wants a total of 16 to 32 active connections across all application pods, and each pod's maximumPoolSize is that total divided by the pod count.

Then validate against Little's law: needed connections equal request rate times average connection hold time, so 300 requests per second holding a connection for 30 ms needs about nine.

If that number exceeds what the database allows, the fix is to hold connections for less time — fewer statements, delayed acquisition, no remote calls — not a bigger pool.

A pool larger than the database's parallel capacity just moves the queue from Hikari to the database's lock and CPU scheduler, where it is harder to see. I put PgBouncer in front when pod counts are large.

"What alert would have caught this before users timed out?"

Hikari's Micrometer metrics: hikaricp.connections.pending greater than zero for more than thirty seconds, and hikaricp.connections.usage — the time a connection is held per borrow — with a p99 above, say, 200 ms. Pending is the leading indicator; timeouts are the lagging one.

I would also alert on hikaricp.connections.acquire p99, which is the wait to borrow, and on the ratio of active connections to database active sessions, because "pool full, database idle" is exactly the signature of connections held during non-database work.

For the root cause, Hikari's leakDetectionThreshold=2000 logs a stack trace for any connection held longer than two seconds, which points straight at the transactional method with the gateway call.

"What does the pool look like with virtual threads and thousands of concurrent requests?"

The same, only faster to fail. Virtual threads remove the thread-count ceiling, so instead of two hundred requests queueing on Tomcat's thread pool, ten thousand arrive at Hikari at once; the pool of ten serves them in turn, and the rest wait up to connectionTimeout.

Throughput is unchanged because the bottleneck was the connection hold time, not the threads. Where virtual threads help is that a thread waiting on Hikari or on the gateway costs almost nothing, so the service does not fall over from thread exhaustion while it waits.

The design consequence is that back-pressure must move to an explicit limit — a bulkhead semaphore around the transactional call, sized to the pool — so requests fail fast rather than queue for thirty seconds. Spring Boot 4 enables virtual threads with spring.threads.virtual.enabled=true.

Q19. "What does Spring do with a checked exception thrown inside a @Transactional method, and why does that interact badly with the flush?"

Reveal answer

Strong answer By default Spring rolls back only on unchecked exceptions — RuntimeException and Error. A checked exception propagating out of a @Transactional method triggers a commit, unless rollbackFor names it.

The commit runs the flush, so every change made to managed entities before the exception is written to the database: a method that updated an order's status, then threw a checked PaymentDeclinedException, ends with the status change persisted and the exception delivered — a half-completed business operation that looks atomic in the code.

The second interaction is worse: if the flush itself fails during that commit — a constraint violation on a row the method never meant to keep — the original checked exception is replaced by a DataIntegrityViolationException, and the real cause is lost.

The rule is simple: throw unchecked exceptions from transactional code, or declare @Transactional(rollbackFor = Exception.class), and never catch an exception inside a transactional method and continue, because a RuntimeException that reached the proxy has already marked the transaction rollback-only, and the eventual commit throws UnexpectedRollbackException.

Land it Checked exceptions commit by default — a rule inherited from EJB that every senior engineer should override with rollbackFor.

Likely follow-ups
"Why did Spring choose to commit on checked exceptions?"

It inherited the rule from EJB, where checked exceptions were "application exceptions" that represented expected business outcomes — insufficient funds, item not found — and unchecked exceptions were "system exceptions" that meant something broke.

Under that model the transaction should commit on an application exception, because the work done before it is still valid; only a system failure justifies undoing everything. Spring kept the default for compatibility, and its authors have said the choice is debatable.

The problem is that modern Java code rarely follows that discipline, so the distinction between checked and unchecked has nothing to do with whether the work should be kept.

That is why I set rollbackFor = Exception.class as the team default, or in Spring 6.2 and later use the rollbackFor element on a meta-annotation the team shares.

"How do you find every @Transactional method in the codebase that could commit on a checked exception?"

An ArchUnit test: for every method or class annotated @Transactional without rollbackFor covering Exception, check whether the method declares a checked exception in its throws clause or calls a method that does; fail the build with the list.

A cheaper first pass is a grep for throws on methods in @Service classes.

Then the runtime check: Spring's TransactionInterceptor logs at DEBUG when it decides "Completing transaction" after an exception, and a log filter for "commit" combined with an exception on the same request finds the live cases.

Fixing them is mechanical — add rollbackFor or wrap the checked exception in a domain RuntimeException at the boundary.

"Explain UnexpectedRollbackException from the mechanism up."

An inner REQUIRED method throws a runtime exception; the transaction interceptor around it sees the exception and, because the transaction belongs to an outer caller, does not roll back but marks the shared transaction rollback-only through TransactionStatus.setRollbackOnly().

The outer method catches the exception and continues, believing it recovered. When the outer method returns, its interceptor calls commit; AbstractPlatformTransactionManager sees the rollback-only flag, performs a rollback instead, and throws UnexpectedRollbackException to tell the caller its commit did not happen.

Nothing the outer method did after the catch is saved. The fixes are: do not catch and continue, or make the inner method REQUIRES_NEW if its failure really is independent, or use noRollbackFor on the inner method when the exception is a normal outcome.

"Where does a constraint violation from the flush actually surface, and what exception type?"

It surfaces at commit inside the transaction interceptor, after the service method has returned, unless something forced an earlier flush.

Hibernate throws ConstraintViolationException; Spring's JpaTransactionManager translates it through HibernateJpaDialect into DataIntegrityViolationException, and the specific subtype depends on the dialect's SQL-state mapping — a unique index violation on PostgreSQL, SQL state 23505, becomes DuplicateKeyException.

Because it happens outside the method, a try/catch in the service never sees it; the place to handle it is the caller, a @ControllerAdvice, or a non-transactional wrapper that catches and retries.

If the method needs to react itself, it calls em.flush() explicitly at the point where the violation is expected and catches there.

Q20 · Scenario. "A method annotated @Transactional runs a JPQL update through a @Modifying query, then reads the same entity with findById and sees the old value. Explain and fix."

Reveal answer

Strong answer Symptom: a bulk update is invisible to a subsequent read in the same transaction. Evidence: the SQL log shows the UPDATE executed and, for the read, either no SELECT at all or a SELECT whose result was discarded.

Cause: the entity was already in the persistence context — loaded earlier in the transaction, or by a query that returned it — and a JPQL bulk update runs straight against the database, bypassing the context; it neither updates the managed object's fields nor invalidates it.

findById then serves the stale instance from the identity map without asking the database. Fix: @Modifying(clearAutomatically = true, flushAutomatically = true).

flushAutomatically writes pending changes before the bulk statement so the update does not overwrite them; clearAutomatically empties the context afterwards so the next read reloads from the database.

The cost is that every entity loaded before the update is now detached, so hold no references across the call. Prevention: bulk updates live in their own small transactional methods, and services that need the entity afterwards reload it.

Land it Bulk JPQL and the persistence context do not talk to each other — clear the context or keep them in separate transactions.

Likely follow-ups
"They added clearAutomatically and now a LazyInitializationException appears later in the same method. Why?"

Because clear() detached every entity in the context, including one the method loaded before the bulk update and still holds a reference to.

Its lazy collections and proxies now point at a session that has no record of them, so touching order.getLines() after the bulk update throws even though the transaction is still open.

The fix is to reload after the bulk statement — findById again, which now issues a fresh SELECT — or to restructure so the bulk update runs first and the entity loads happen afterwards, or to put the bulk update in its own small transactional method.

It is a good example of why clearAutomatically is a sharp tool, and why a method should hold no entity references across a @Modifying call.

"Why does flushAutomatically matter — what could be overwritten?"

Suppose the method set order.setNotes("expedite") on a managed order and then ran update Order o set o.status = 'CANCELLED' where o.id = :id.

Without a flush the bulk UPDATE goes first, and the dirty check at commit later writes the managed object's full column set — including its stale status, PENDING — over the cancellation, because full-column updates write every field.

With flushAutomatically = true, the note change is flushed before the bulk statement, and with clearAutomatically = true the stale object is gone so nothing overwrites the bulk change at commit.

Hibernate's own AUTO flush would have flushed anyway if the query spaces overlapped, which they do here, so the Spring flag matters mostly for FlushModeType.COMMIT sessions and for native queries with declared spaces.

"Would 'update versioned' have helped here?"

Not with the stale read, but with the overwrite. update versioned Order o set o.status = 'CANCELLED' bumps the version column on every affected row.

The managed object in the context still has the old version, so when the dirty check at commit issues its UPDATE with where id = ? and version = ?, the count is zero and Hibernate throws OptimisticLockException instead of silently overwriting the cancellation.

That turns a data-loss bug into a loud failure, which is better, but the method still reads the old status from the identity map. So the complete answer is update versioned for safety against other writers, plus clearAutomatically or a reload for correctness inside this transaction.

"When is a bulk JPQL update the right choice over load-and-modify at all?"

When the change is set-based and uniform: cancel every order older than ninety days, mark all pending jobs as stale, increment a counter. One statement replaces N loads and N updates, no entities enter the context, and the database applies it with one plan.

It is the wrong choice when the change depends on per-row state that lives in domain logic, when lifecycle callbacks, Envers auditing, or Spring Data auditing must fire, when a cascade is expected, or when the same transaction needs the updated entities afterwards.

I keep bulk updates in dedicated repository methods with a name that says so — cancelAllOlderThan — in their own transaction, and I never mix a bulk update and entity manipulation of the same table in one method.

Drill · merge, save & detached entities

This group tests whether you know what Spring Data's save() actually does with the object you pass it, because that one method hides both persist and merge.

Q21. "Explain exactly what SimpleJpaRepository.save() does, and the SQL it can generate in each branch."

Reveal answer

Strong answer save(entity) asks entityInformation.isNew(entity). The default rule says new when the id is null, or a primitive id is zero, or — if the entity has a wrapper-typed @Version — the version is null. If the entity implements Persistable, its own isNew() decides.

New: em.persist(entity), which schedules an INSERT (sent at persist time for IDENTITY, at flush for SEQUENCE) and returns the same object, now managed. Not new: return em.merge(entity).

Merge first looks in the identity map; on a miss it issues a SELECT by id to load the current row; then it copies every field from your object onto the managed one and returns the managed copy.

At flush, the dirty check between that copy's snapshot and the copied values yields an UPDATE — or, if you passed an unchanged detached object, nothing. If the SELECT finds no row, merge treats the object as new and INSERTs it with your id.

So save() on a detached entity costs a SELECT plus an UPDATE, and save() on an entity with a pre-assigned id that does not exist yet costs a wasted SELECT plus an INSERT.

Going deeper One branch of merge is often stated loosely: what happens when the SELECT finds no row. Hibernate's DefaultMergeEventListener then treats the object as transient and persists a copy.

For an entity with an assigned id, the copy carries your id and the INSERT uses it.

For an entity with @GeneratedValue, Hibernate ignores the id you set and generates a new one, so the row appears under a different id than the one the caller believes it has — a silent mismatch that surfaces later as "not found".

Also worth knowing as of Aug 2026: Spring Data JPA 3.x and 4.x still decide isNew exactly as described, and Jakarta Persistence 3.2, which Hibernate 7 implements, adds EntityManager.getReference(entity) and getVersion(entity), which give a service a cheap way to check the client's version against the loaded one before deciding to merge.

The way to verify which branch ran is Statistics.getEntityLoadCount() — a merge miss shows a load that returned nothing, followed by an insert — or simply asserting assertSame(entity, saved), which holds only on the persist branch.

what save() actually doesruns offline
// SimpleJpaRepository.save is NOT an INSERT. It is:
@Transactional
public <S extends T> S save(S entity) {
    if (entityInformation.isNew(entity)) {
        em.persist(entity);        // TRANSIENT -> managed. Returns void; entity is managed.
        return entity;
    } else {
        return em.merge(entity);   // DETACHED -> copies state onto a managed instance
    }
}
// isNew() is, by default, "is the @Id null?" (or zero for a primitive).

// THE SQL EACH PATH PRODUCES:
//
// persist():  INSERT ... (at flush, or immediately with GenerationType.IDENTITY)
//
// merge():    SELECT ... where id = ?        <- an extra read you did not ask for
//             UPDATE ... where id = ?
//             ...because merge must load the current row to copy your state onto it.

// CONSEQUENCE 1 — merge RETURNS A DIFFERENT OBJECT. The argument stays detached.
Order saved = repo.save(detachedOrder);
saved.setStatus(PAID);          // tracked
detachedOrder.setStatus(PAID);  // NOT tracked -- silently lost
// Always use the returned value.

// CONSEQUENCE 2 — calling save() on an ALREADY MANAGED entity is pointless:
@Transactional
public void confirm(Long id) {
    Order o = repo.findById(id).orElseThrow();
    o.setStatus(CONFIRMED);
    repo.save(o);                // no-op: dirty checking would have done it anyway
}
// Harmless here, but in a loop it is a merge per element and a wasted SELECT each.

// CONSEQUENCE 3 — with an assigned id (a client-generated UUID) isNew() is
// false for a genuinely new entity, so save() calls merge(), which issues a
// SELECT that finds nothing before every INSERT. That is the Q22 slowdown.
// Fix: implement Persistable<ID>, or use a time-ordered UUID with @CreatedDate.

Consequence 3 halves insert throughput and is invisible in the code. Switching to client-generated ids silently changes every save() from a bare INSERT into a SELECT followed by an INSERT, which is exactly the symptom in Q22.

Land it save() is persist-or-merge chosen by isNew(), and the merge branch always pays a SELECT you may not have expected.

Likely follow-ups
"What does saveAll() do differently, and is it batched?"

saveAll() is a loop that calls save() per element inside one transaction, so each element goes through the same isNew decision, and each merge branch pays its own SELECT. It is batched at the JDBC level only if hibernate.jdbc.batch_size is set and the ids are not IDENTITY; Spring Data itself does nothing special.

With SEQUENCE ids and allocationSize = 50, five hundred new entities cost ten sequence calls and ten batched INSERTs of fifty rows each, provided order_inserts=true when mixed entity types are involved. With IDENTITY it is five hundred round trips regardless.

The persistence context also grows by the whole list, so for tens of thousands of rows I use a manual loop with flush() and clear() every batch, or a StatelessSession.

"How does isNew work with a primitive long id versus a Long?"

For a wrapper Long, new means null. For a primitive long, new means zero, because Spring Data's JpaMetamodelEntityInformation checks primitive number ids against zero. That works until a legitimate id of zero exists, or until someone constructs an entity with an explicit id.

The trap is an entity with a primitive id and a manually set value: Spring picks merge, Hibernate SELECTs, finds nothing, and generates a fresh id, so the entity ends up under a different id than intended.

A wrapper-typed @Version field takes precedence over the id check entirely: if it is null the entity is new, which is why a version of Long type on a UUID-keyed entity rescues isNew. I standardise on Long ids and Long or Integer versions.

"What SQL does save() produce for a managed entity that has a lazy collection with CascadeType.MERGE?"

The merge cascade walks the collection.

If the collection is uninitialised, Hibernate must initialise it to cascade into its elements, so you get a SELECT of all the children — five hundred lines for an order — even though nothing changed, followed by no UPDATE because the dirty check finds everything equal.

If the children themselves have MERGE cascades, the walk continues down. That is the "harmless save that costs a query" from Q24, and it is why a save() after a small status change on an aggregate root can be the slowest statement in the request.

The SQL log shows it as a SELECT of the child table right after the service call; the fix is to drop the redundant save() or limit the cascade to PERSIST and REMOVE.

"Can you make save() always persist, for entities you know are new?"

Yes, three ways. Implement Persistable<ID> with an isNew() that returns true until @PostPersist or @PostLoad flips a transient flag; Spring Data checks that interface first.

Or add a custom repository fragment with a method that calls em.persist() directly — I usually name it insert() to make the intent explicit, since Spring Data JPA has no built-in insert method the way Spring Data JDBC does.

Or, in Hibernate 7, use StatelessSession.insert() for bulk paths. Whichever way, the point is that the "is this new?" question is answered by the code that knows the answer, not by inspecting the id.

Q22 · Scenario. "A team switched primary keys to client-generated UUIDs. Insert throughput halved and the SQL log shows a SELECT before every INSERT. Diagnose and fix."

Reveal answer

Strong answer Symptom: one SELECT per INSERT after moving to assigned UUIDs. Evidence: the SQL log pairs select ... where id=? returning nothing with each insert; statistics show entity load count equal to insert count.

Cause: with the id set before save(), Spring Data's isNew() returns false, so save takes the merge path, and merge must SELECT to find out whether a row exists before deciding between UPDATE and INSERT. Fix, best first: implement Persistable<UUID> on the entity with a @Transient boolean isNew = true field, flipped to false in @PostPersist and @PostLoad callbacks, so save calls persist directly for fresh objects.

Alternatively, let Hibernate generate the id with @GeneratedValue @UuidGenerator(style = VERSION_7) so the id is null before persist and isNew works by default. Or call em.persist() directly through a custom repository fragment for the bulk path.

Also make sure the column is a native uuid type and, if a wrapper-typed @Version exists, that it is null on new objects, since that alone would have rescued isNew. Prevention: a statement-count test on the create path.

Land it Assigned ids break isNew() — tell Spring Data what new means with Persistable, or let Hibernate generate the UUID.

Likely follow-ups
"They implemented Persistable and the SELECT is gone, but now updates of loaded entities INSERT duplicates. What went wrong?"

The isNew flag is not being cleared on load.

The implementation must flip the transient flag to false in both @PostPersist and @PostLoad; if only @PostPersist is handled, an entity loaded from the database still reports isNew() == true, so save() calls persist on it, and Hibernate either throws "detached entity passed to persist" or, when the id is assigned, tries an INSERT that fails on the primary key.

The other common mistake is using a non-transient field for the flag, which then maps to a column. The verification is a test that loads an entity, calls save(), and asserts zero inserts. Spring Data's own AbstractPersistable base class shows the reference implementation.

"Why did throughput halve rather than drop by some other factor?"

Because each create became two round trips instead of one, and the round trip dominated.

A SELECT by primary key on an indexed UUID column is fast on the server — tens of microseconds — but the network round trip is a millisecond or more, so the cost of a create is approximately two network trips instead of one.

If the INSERTs had been JDBC-batched before the change, the drop would have been much worse than half: batching sends fifty inserts in one trip, while the merge path's SELECT cannot be batched, so fifty creates go from one trip to fifty-one.

The measurement to make is statements per create from statistics, and round-trip latency from pg_stat_statements mean time versus the client-observed time.

"Should the UUID be generated by the client, the application, or the database?"

The application, in the entity constructor, with a version-7 UUID. Client generation means trusting the caller with primary keys, which invites collisions and lets a client choose ids that sort badly; database generation, such as gen_random_uuid() or PostgreSQL 18's uuidv7(), forces an IDENTITY-like round trip and disables insert batching.

Application generation gives the id before the INSERT, so it can be placed in outbox rows, log lines and response bodies immediately, and inserts batch normally.

Hibernate 7's @UuidGenerator(style = VERSION_7) does this for you while keeping the id null before persist, so isNew works with no Persistable at all. For a client-supplied idempotency key, store it in its own unique column rather than using it as the primary key.

"How would you prevent this regression from reaching production again?"

A statement-count test on the create path — assertSelectCount(0) and assertInsertCount(1) per entity — using the Hibernate statistics or hypersistence-utils' validator, run in CI against Testcontainers. Plus a throughput benchmark in the performance environment that inserts, say, ten thousand rows and asserts a floor.

And a code review checklist item: any entity whose id is set before save() must either implement Persistable, use a Hibernate generator, or be inserted through an explicit persist fragment.

The first catches it before merge, the second catches anything the first missed, and the third keeps the knowledge in the team rather than in one person's head.

Q23. "A controller deserialises JSON into an Order entity and calls save(). What is wrong with that design from the persistence context's point of view?"

Reveal answer

Strong answer The deserialised object is a detached entity with whatever fields the client sent, so save() takes the merge path and copies every field onto the managed row — including the ones the client did not send, which are null or default in the JSON object.

A client that posts only a new status wipes the customer reference, the total and the created-at timestamp. With @Version, the client must also echo the correct version or the merge fails; without it, the client silently overwrites concurrent changes.

Cascades on the entity make it worse: a JSON payload containing a lines array becomes a merge of each line, and orphan removal deletes any line the client omitted.

Beyond persistence, the entity becomes the API contract, so renaming a column changes the JSON and vice versa.

The right shape is a request DTO — a record with exactly the editable fields — a service method that loads the managed entity inside a transaction and applies the change through a method like order.markPaid(), and dirty checking writing only what changed. E6 makes the contract argument from the API side.

Land it Merging a client-supplied entity is a bulk overwrite by whatever the client forgot to send — load, mutate, let the dirty check write.

Likely follow-ups
"What if the team insists on binding JSON to the entity — what is the minimum you would require?"

At minimum: the id and version must come from the path and an If-Match header, not from the body, and the service must load the managed entity and copy only an explicit allow-list of fields onto it — never call merge on the deserialised object.

Jackson must be configured with @JsonIgnoreProperties on the associations and with FAIL_ON_UNKNOWN_PROPERTIES so a client cannot smuggle a field. Cascades on the entity must not include MERGE. And an ArchUnit rule should forbid @RequestBody parameters of @Entity type in controllers so the exception stays contained.

At that point you have written a DTO with extra steps, which is the argument for just writing the DTO.

"How would you handle a partial update, a PATCH, correctly?"

With a DTO that can distinguish "absent" from "null". A record with Optional fields or a JsonNullable wrapper from the jackson-databind-nullable module tells the service whether the client omitted notes or explicitly set it to null.

The service loads the managed entity in a transaction, applies each present field through a domain method, and lets the dirty check write only the changed columns — with @DynamicUpdate if the row is wide.

For JSON Merge Patch semantics, RFC 7386, null means remove and absent means keep, which maps directly.

For concurrency, the PATCH carries the version as an ETag and the service compares it to the loaded entity before applying, returning 412 if it differs, which is Q73's design.

"Is there a Spring Data feature that maps between DTOs and entities safely?"

Spring Data offers projections for reading — interface projections, record projections, and Class-based DTO queries — but nothing for writing; that is deliberate, because a write should go through the aggregate's methods.

For mapping code, MapStruct generates the copy from a DTO onto an existing entity with @MappingTarget and nullValuePropertyMappingStrategy = IGNORE, which is safe as long as the target is the managed entity loaded in the transaction and the mapping is field-by-field.

What I avoid is any tool that constructs a fresh entity from JSON and hands it to save(). As of Aug 2026, Jakarta Data repositories in Hibernate 7 follow the same philosophy: insert, update and save are distinct methods so the intent is explicit.

"What actually happens to the version when the client sends an old one through merge?"

Merge copies the client's version onto the managed entity's state only for comparison: Hibernate checks the detached version against the loaded version during merge, and if they differ throws OptimisticLockException immediately, before flush — that is one of the few places the exception surfaces inside the service method. If the client sends no version at all, the null is treated as "new entity" by Spring Data's isNew when the version field is a wrapper, so save() calls persist and Hibernate complains about the assigned id, or with an assigned-id mapping tries to INSERT a duplicate. Either way the client-controlled version is an attack surface: a malicious client can always echo the current version by reading first, which is why the version protects against accidents, not adversaries.

Q24. "When is calling save() on an already-managed entity harmless, and when does it actually cost something?"

Reveal answer

Strong answer For a managed entity with a generated id, save() resolves to merge(), and merge on a managed instance is a no-op that returns the same object — Hibernate finds it in the identity map and there is nothing to copy.

So the call is harmless, and the eventual UPDATE comes from dirty checking whether or not you called it. It costs something in three cases.

First, cascades: merge cascades along CascadeType.MERGE or ALL relationships, walking every reachable entity and collection, which initialises lazy collections — a save on an order with a lazy list of 500 lines loads all 500 lines just to discover nothing changed.

Second, when the method was not transactional, the repository's own transaction commits the change immediately, so save() is not harmless but load-bearing, and the code's correctness now depends on which calls happen to be inside a transaction.

Third, readability: a codebase that calls save on every managed entity trains readers to believe save is required, and they will forget it in the one place a merge of a detached object really was needed.

Land it save() on a managed entity is free until it cascades into a lazy collection — then it is the N+1 you did not know you asked for.

Likely follow-ups
"How would you detect the cascade-initialised collection cost in a running system?"

Statistics: getCollectionFetchCount() climbing on a write endpoint that should not read collections is the signature.

Per request, a query-count filter that logs the number of statements and the collection roles fetched — Hibernate's org.hibernate.stat DEBUG output names the role, such as Order.lines — pins it to the endpoint.

The confirmation is removing the save() call in a test and watching the SELECT disappear. In production I would look at pg_stat_statements for a select ... from order_line where order_id = ? whose call count matches the update endpoint's request count rather than the read endpoint's; that mismatch is the tell without touching any code.

"Is there any case where you would call save() on a managed entity deliberately?"

One: when I want the return value's type. Some teams write return repo.save(order) at the end of a method for symmetry with the create path, and the cost is nil if the cascades are narrow.

Another borderline case is a method that may receive either a managed or a detached entity — a bad design, but in legacy code save() is the call that handles both.

What I would never do is call it to "force the update", because it does not; the flush does.

If someone needs an UPDATE to go out at a specific point, the explicit call is em.flush(), and the reason should be written in a comment, because a flush in the middle of a method is unusual enough to deserve one.

"What does save() return on the merge branch, and why does that matter for the caller?"

The managed copy, which is a different object from the argument when the argument was detached.

A caller that keeps using its own object — setting more fields, adding it to a collection, returning it — is working with a detached instance whose later changes are ignored, and whose version is stale. So the caller must reassign: order = repo.save(order).

Static analysis rules such as Error Prone's CheckReturnValue or a custom ArchUnit test can flag an ignored save() result, and Spring Data documents that the return value must be used.

On the persist branch it returns the same reference, which is why code that ignores the result works for creates and fails mysteriously for updates.

"How does this change with Hibernate 7 and Jakarta Data repositories?"

Jakarta Data, which Hibernate 7 implements and Spring Boot 4 can use alongside Spring Data as of Aug 2026, separates the operations that save() conflates: @Insert methods call persist and fail on an existing id, @Update methods fail if the row does not exist, and @Save is the upsert-like behaviour.

They also default to StatelessSession-style semantics in Hibernate's implementation, so there is no persistence context to be "already managed" in — every call is a statement. That removes the ambiguity this question is about, at the cost of losing dirty checking, which is a real trade.

In a Spring Data codebase, I get most of the clarity by naming: a custom insert() fragment for creates and no save() calls on the update path.

Q25 · Scenario. "PersistentObjectException: detached entity passed to persist — the stack trace comes from repository.save() on a brand-new object. How is that possible?"

Reveal answer

Strong answer Symptom: persist rejects an object the code just constructed. Evidence: check whether the object has an id set before save, and check the cascade settings on its relationships.

Ranked causes: one, the object's id was assigned manually — setId(...) from a request — while the mapping says @GeneratedValue; Hibernate sees a generated-id entity that already has an id and concludes it must be detached, and Spring Data's isNew would have chosen merge only if the id type made it non-null — a primitive long id set to 7 is "not new" to Spring but a mismatched entity to Hibernate; two, the new object references an existing entity through a relationship with CascadeType.PERSIST or ALL, and that referenced entity is detached — a customer loaded in a previous transaction — so persist cascades to the detached customer and throws there, with the trace pointing at the outer save; three, the same new object was saved twice across two transactions.

Fix: never set generated ids by hand; replace the detached reference with getReferenceById(customerId) inside the current transaction; drop PERSIST cascade on many-to-one relationships, where it almost never belongs. Prevention: no cascade on @ManyToOne, as a review rule.

Land it The "detached entity" is usually not the one you saved but one it cascades to — follow the cascade, not the stack trace.

Likely follow-ups
"You removed the cascade and now the customer reference is not saved at all. What happened?"

Nothing needed to be saved — the customer already exists — but the order now carries a reference to a detached customer object, and without a cascade Hibernate must decide what to write in customer_id.

It writes the detached object's id, which works, because to-one associations are written from the referenced entity's identifier, and Hibernate does not require the target to be managed for that.

If the column came out null, the more likely cause is that the customer object had no id at all — a transient customer built from a DTO — in which case Hibernate throws TransientPropertyValueException at flush rather than writing null.

Either way the clean pattern is customerRepo.getReferenceById(dto.customerId()) inside the transaction, which gives a managed proxy with no SELECT.

"Why does Hibernate decide the object is detached just because it has an id?"

Because with a generated id, an id can only have come from a previous persist. Hibernate's persist asks the entity's identifier generator whether the current id value is the "unsaved value"; for generated ids that is null, or zero for primitives, or whatever @GeneratedValue declares.

A non-null value means the entity was persisted at some point, and since it is not in this context, it must be detached. There is no SELECT involved; it is an inference from the id.

With assigned ids, the unsaved value is unknowable, so Hibernate consults the version field if present, and otherwise assumes transient and inserts.

That is why the same code behaves differently for @GeneratedValue and for assigned UUIDs, and why setting a generated id by hand is always wrong.

"How would you make the stack trace point at the real culprit?"

The exception message names the entity: "detached entity passed to persist: com.shop.Customer", so the first thing is to read the class name in the message rather than the top frame. Then logging.level.org.hibernate.event.internal.DefaultPersistEventListener=TRACE shows the cascade walking from the order into the customer. In tests, an assertion that em.contains(order.getCustomer()) is true before save() pins it exactly. For prevention, I make the failure impossible: no CascadeType.PERSIST on @ManyToOne and @ManyToMany, enforced with an ArchUnit rule that inspects the annotation's cascade attribute on those field types.

"The same object was saved twice across two transactions — walk me through why the second fails."

The first transaction persists the transient object, the generator assigns id 42, the INSERT runs, and at commit the context closes and the object becomes detached with id 42.

The caller, perhaps a retry loop or a test that reuses a fixture, calls save() again in a new transaction.

Spring Data sees a non-null id and calls merge, which would work — SELECT, copy, no-op UPDATE. But if the code calls em.persist directly, or the repository fragment does, Hibernate sees a generated-id entity with id 42 that is not in the new context and throws.

So the trace shows a persist on an object that was "brand new" a moment ago in a different transaction. The cure is to not reuse entity objects across transactions; reload by id.

Q26. "Compare update-by-load-and-modify with update-by-merge for a REST PUT of an order. Which costs fewer statements, and which is safer?"

Reveal answer

Strong answer Both cost the same statements in the simple case: one SELECT to get the current row and one UPDATE at flush.

Load-and-modify does the SELECT through findById and the UPDATE through dirty checking; merge does the SELECT inside merge() and the UPDATE through the same dirty check on the managed copy. The differences are in safety and control.

Load-and-modify lets you apply only the fields the request carries, run business rules against the current state (markPaid() refusing an already-shipped order), and compare the client's version to the loaded one for a deliberate optimistic check.

Merge overwrites every field from the client object, including nulls, cascades into relationships, and gives you no place to enforce rules — the entity is already in its final state when you see it.

Merge wins only when the client legitimately owns the whole object, such as a rich desktop client round-tripping a detached graph, which is the 2005 use case JPA designed it for.

For a modern service with a DTO at the boundary, load-and-modify is both the safer and the clearer option, and the statement count is identical.

Land it Same SQL, different control — load-and-modify keeps the business rules and the field list in your hands.

Likely follow-ups
"Does load-and-modify cost more when the entity has collections?"

Only if you touch them.

findById loads the row with its to-one associations as proxies and its collections uninitialised; a status change that never reads getLines() costs one SELECT and one UPDATE. Merge with CascadeType.MERGE on the collection is the expensive one, because the cascade initialises the collection and merges every element.

If the PUT replaces the whole line list, both approaches must load the lines — load-and-modify to diff them, merge to cascade — but load-and-modify lets you write the diff explicitly and keep the same child ids where the content matches, whereas merge with orphan removal deletes and reinserts anything whose id the client did not echo. The statement counts converge; the control does not.

"How do you carry the optimistic version through a PUT with load-and-modify?"

The client sends the version it read, ideally as an If-Match: "7" header rather than a body field. The service loads the entity, compares order.getVersion() to the header, and returns 412 Precondition Failed if they differ, before making any change.

If they match, it applies the change and lets the flush's own version check guard the millisecond window between the compare and the commit — that second check is what makes the first one safe. The response carries the new version as an ETag.

Without the explicit compare, the failure would still be detected at commit, but as an ObjectOptimisticLockingFailureException thrown from the proxy, which is harder to turn into a clean 409 or 412 and cannot include a helpful message about what changed.

"What would you do differently if the client really does own the whole object, like an offline mobile app syncing?"

Then the request is a document, not an edit, and I would treat it as one: a versioned jsonb or a dedicated sync table keyed by client id and revision, written with a single UPSERT, with conflict detection by revision rather than by row-level dirty checking.

Merging a client-supplied entity graph into normalised tables is where merge came from, and it is workable only with strict rules — every child carries its id, the version is mandatory, and cascades are exactly MERGE plus orphan removal on true compositions.

Even then I would write the merge myself in a service method so that business rules run: "lines of a shipped order cannot change" is not something em.merge can enforce. The upsert-document approach keeps the conflict logic in one place.

"Does the statement count change with @DynamicUpdate or with a projection-first check?"

Not the count, only the width. @DynamicUpdate makes the one UPDATE list only the changed columns in both approaches, since both end in a dirty check on a managed object.

A "check first" design — a projection query for the version, then the load — adds a SELECT, so it is worse unless the check usually fails.

Where the count genuinely changes is a bulk-style PUT: update Order set status = :s where id = :id and version = :v as a @Modifying query is a single statement with no SELECT, at the price of no business-rule execution and no callbacks, which is fine for a simple status flip and wrong for anything with invariants. I use that only for idempotent flag-style fields.

Q27. "What is the difference between em.detach(), em.clear(), and closing the EntityManager, and when would you use each on purpose?"

Reveal answer

Strong answer detach(entity) removes one entity — and, along CascadeType.DETACH relationships, its reachable graph — from the persistence context, discarding any unflushed changes to it.

Use it when a loop loads a large object you have finished with and you want the garbage collector to have it before the transaction ends, or when you want to protect an entity from an accidental later dirty check.

clear() empties the whole context — every entity becomes detached, every pending unflushed action is discarded, which is why it must be preceded by flush() in a batch loop.

Use it every N rows in bulk processing, and after a bulk JPQL update to avoid stale reads. Closing the EntityManager is the end of the unit of work: Spring does it at transaction completion, and you never do it yourself inside a container-managed setup.

The subtle trap with all three: a detached object's lazy proxies still point at the old session; if the session is still open, they lazy-load happily, and if it has closed, they throw. Detaching does not make a proxy safe to hand out.

Land it detach for one object, clear after a flush in loops, and let Spring close — and remember that detaching does not initialise anything.

Likely follow-ups
"What happens if you clear() without flushing first?"

Every queued action is discarded and every entity is detached. A persist that had not flushed yet — a SEQUENCE-generated entity, whose INSERT waits for flush — simply never happens; its id was drawn from the sequence, so you see a gap and no row.

Dirty entities lose their changes silently. An IDENTITY-generated entity's INSERT already ran at persist time, so that row survives, which makes the behaviour differ by id strategy and leads to confusing partial results. There is no exception.

The way to see it is Statistics.getEntityInsertCount() being lower than the number of persist calls. So the rule is mechanical: flush() then clear(), always in that order, and a code review should reject a bare clear() in a write path.

"Does detach() free memory immediately?"

It removes the entity, its EntityEntry and its snapshot from the context's maps, so they become garbage as soon as your own code drops its reference. If a local variable or a list still points at the entity, it stays alive — detached, but not collected.

Collections belonging to the detached entity are also disconnected from the session, but their loaded elements stay in memory with the parent. So detach is a necessary but not sufficient step in a loop; the loop variable must go out of scope too.

A heap histogram after a chunk showing the entity class count still at the previous total means something is holding references, usually a result list from the query that produced them.

"Can you detach just one entity and then continue to use its lazy collection?"

Only while the session is still open, and only by accident. A detached entity's PersistentBag still holds a reference to the Session that created it.

If that session is open, accessing the collection initialises it through the old session, which works but is not something the specification promises and Hibernate 6 and 7 emit no warning about. Once the session closes, the same access throws LazyInitializationException.

So code that detaches and later reads a collection is relying on timing. If the collection is needed, initialise it before detaching — Hibernate.initialize(order.getLines()) or a fetch join — so the detached object is self-contained.

"When would you ever close the EntityManager yourself?"

When I created it myself.

In a Spring application that means an EntityManagerFactory.createEntityManager() in a batch reader, a background job that outlives any request, or a test that needs full control of the lifecycle; each of those goes in a try-with-resources, since EntityManager is AutoCloseable from JPA 2.2 onwards.

Calling close() on the injected shared proxy throws IllegalStateException, because the container owns it.

The related mistake is holding a hand-created EntityManager in a field of a singleton bean, which makes it shared across threads — it is not thread-safe — and keeps its context and connection alive for the life of the process.

Drill · Callbacks, auditing & unit-of-work design

This group tests whether you can bend the lifecycle to your purposes — callbacks, auditing, outbox rows — without fighting the flush.

Q28. "What are the JPA lifecycle callbacks, when exactly does each fire relative to flush, and what must you never do inside one?"

Reveal answer

Strong answer There are seven: @PrePersist fires inside persist(), before the entity is added to the context, so it is the place to set defaults like created-at; @PostPersist fires after the INSERT executes — at persist time for IDENTITY, at flush for SEQUENCE, which is a difference that surprises people writing "after insert" logic; @PreUpdate and @PostUpdate fire during flush, only for entities the dirty check found changed; @PreRemove at remove() and @PostRemove after the DELETE at flush; @PostLoad after the entity's state is loaded from a query or find, and again after refresh(). They can live on the entity, on a @MappedSuperclass, or in a separate @EntityListeners class, which is how Spring Data's AuditingEntityListener fills @CreatedDate and @LastModifiedBy. Never do three things inside one: call the EntityManager — persist, query, or flush — because you are inside a flush and re-entering it is undefined and in Hibernate throws or corrupts the queue; touch lazy associations that may trigger loads mid-flush; or perform I/O like sending an event, because the transaction may still roll back after the callback ran.

Land it Callbacks are for setting fields on the entity itself; anything that needs the session or the outside world belongs in a transaction synchronisation after commit.

Likely follow-ups
"How does Spring's AuditingEntityListener get the current user inside a callback?"

Through an AuditorAware<T> bean you register with @EnableJpaAuditing.

At @PrePersist and @PreUpdate time the listener calls auditorAware.getCurrentAuditor(), which typically reads the principal from SecurityContextHolder, and sets the @CreatedBy and @LastModifiedBy fields; @CreatedDate and @LastModifiedDate come from a DateTimeProvider, which defaults to the system clock and can be replaced in tests.

Because the callback runs at flush, on the thread that owns the transaction, the security context is available in a request but not in an @Async or scheduled job unless you propagate it, so those paths see an empty auditor.

The listener class is instantiated by Hibernate, and Spring injects into it through SpringBeanContainer, which Boot configures automatically.

"What if I really need to persist another entity in reaction to an update?"

Do it outside the flush. Two clean options.

Publish a Spring application event from the domain method that made the change — not from the callback — and handle it with a @TransactionalEventListener(phase = BEFORE_COMMIT), which runs before the commit's flush in the same transaction and can persist normally.

Or register a TransactionSynchronization whose beforeCommit does the extra persist, which is what Envers effectively does through its own flush-time integration. Hibernate's own Interceptor and event listener SPI also allow it at onFlushDirty with care, but that is framework-level code.

Inside a JPA callback, the only safe reaction is setting fields on the entity you were handed.

"Does @PreUpdate fire if only a collection changed?"

Not by default.

The dirty check that decides @PreUpdate looks at the entity's own columns; a change inside a @OneToMany collection is a change to the child rows, or to a join table, not to the parent's row, so the parent is not dirty and its callback does not run.

Adding an element to an @ElementCollection or a @ManyToMany — where the parent owns the collection table — still does not mark the parent's row dirty.

If the business needs "order modified" to fire on line changes, the domain method that adds a line should also touch a parent field, such as updatedAt, or the root should be locked with OPTIMISTIC_FORCE_INCREMENT, which bumps the version and therefore counts as an update.

"How would you test callback ordering and timing?"

With an integration test that records a list of events.

A test-only @EntityListeners class appends the callback name and System.nanoTime() to a static list; the test persists an entity with SEQUENCE ids, asserts that @PrePersist was recorded but @PostPersist was not, calls em.flush(), and then asserts @PostPersist appeared — that proves the flush-time timing.

The same test with an IDENTITY entity shows @PostPersist before the flush. For @PreUpdate, assert it is absent after a no-op change and present after a real one.

This kind of test is cheap and catches the surprising behaviours the question is about before someone builds an "after insert" feature on the wrong assumption.

Q29 · Design. "Design audit history for the orders aggregate: every change to an order must be recorded with who, when, and what changed, queryable for seven years."

Reveal answer

Strong answer Requirements: capture every committed change to orders and lines, attribute it to a principal and a time, never lose an audit row for a committed change, keep queries on the live table fast, and retain seven years, which for a busy shop is hundreds of millions of rows.

Design: an append-only order_audit table — id, order_id, revision, changed_at, changed_by, change_type, and a jsonb diff of before and after — written in the same transaction as the change so the audit and the change commit or roll back together.

Implementation choices, in order of preference: Hibernate Envers, which does exactly this with @Audited, a shared REVINFO table, and a per-entity _AUD table capturing full snapshots, and gives AuditReader queries for free; or a hand-written @EntityListeners that records diffs into a transaction-scoped buffer and flushes it via a TransactionSynchronization in beforeCommit, which avoids calling the EntityManager inside a callback; or database triggers, which catch writes that bypass the ORM — bulk JPQL, migrations, DBA sessions — but put logic in the database.

Partition the audit table monthly on changed_at and archive old partitions to object storage. Trade-offs: Envers doubles the tables and slows writes by roughly one INSERT per audited entity per transaction; triggers are ORM-proof but harder to test.

What I would not do: fire audit events to a message broker from a @PostUpdate callback, because the transaction can still roll back after the message leaves, and the audit would then describe a change that never happened.

Land it Audit rows commit with the change or not at all — Envers for an ORM-only write path, triggers when anything else can write.

Likely follow-ups
"Requirement change: auditors must also see changes made by a nightly bulk job that uses JPQL updates. Does the design hold?"

Not the Envers-only version. Envers hooks Hibernate's flush events, so a bulk JPQL or native UPDATE bypasses it entirely and the audit table shows nothing for those rows. Two fixes.

Either rewrite the nightly job as an entity-based flush-and-clear loop, which restores Envers coverage at the cost of N statements, or add database triggers on orders and order_line that write to the same audit table for any UPDATE or DELETE, with a session variable such as SET LOCAL app.user = 'nightly-job' so the trigger can attribute it.

I would take the trigger route for completeness and keep Envers for the rich per-revision queries, accepting two write paths into audit. The test is a bulk update in an integration test followed by an assertion on the audit table.

"What would you cut if you had two days?"

I would ship Envers with @Audited on Order and OrderLine, a custom RevisionEntity carrying the username and a request id, and no partitioning, no archival and no triggers.

That gives who, when and what for every ORM write in an afternoon, with AuditReader queries for the auditors.

I would log the two known gaps — bulk statements are invisible, and the tables will need partitioning before the row count reaches the hundreds of millions — as tickets with a date.

What I would not cut is the same-transaction guarantee: an asynchronous audit feed is faster to build and wrong in exactly the cases auditors care about, so the two-day version must still write the audit rows in the transaction.

"How does Envers actually store a change, and what does a query for 'the order as of last Tuesday' cost?"

On each flush, Envers writes one row per changed audited entity into orders_AUD with the entity's full column set, a REV number, and a REVTYPE of 0, 1 or 2 for add, modify or delete, plus one REVINFO row per transaction with the timestamp and your custom fields. The default audit strategy needs a subquery for "as of" reads — the latest revision below the target for each entity — while the ValidityAuditStrategy adds REVEND and an end timestamp to each audit row so the query becomes a range scan on (id, REV, REVEND); it costs an extra UPDATE per change to close the previous row. For seven years of history, that validity strategy plus an index on (order_id, REVEND) is what keeps point-in-time queries fast.

"How would you verify the audit trail is complete in production?"

With a reconciliation job rather than trust. Nightly, sample a thousand orders whose updated_at is within the day and assert each has an audit revision at or after that timestamp; any miss is a write path that bypassed auditing.

Compare the count of distinct REV values in REVINFO with the count of committed write transactions on the table from pg_stat_user_tables.n_tup_upd and n_tup_ins, which should be in the same order of magnitude.

And a canary: a synthetic order updated by every write path — API, bulk job, admin tool — whose audit rows are checked by a scheduled test.

Retention is verified by a query that the oldest partition still present is no older than seven years plus the archival window.

Q30 · Design. "Design the transactional outbox for the orders service: after an order is paid, a Kafka event must be published exactly once from the database's point of view."

Reveal answer

Strong answer Requirements: no event without a committed order change, no committed change without an eventual event, and no reliance on a two-phase commit between the database and Kafka.

Design: an outbox table — id (UUID v7 for ordering), aggregate_type, aggregate_id, event_type, payload jsonb, created_at, published_at nullable.

In the same @Transactional method that calls order.markPaid(), persist an OutboxEvent entity; because both are in the same persistence context they flush in the same JDBC transaction, and atomicity is the database's, not mine.

A relay then moves rows to Kafka: either Debezium tailing the write-ahead log of the outbox table (no polling, lowest latency, one more component), or a polling publisher that runs every 200 milliseconds, selects unpublished rows with PESSIMISTIC_WRITE and skip-locked so several instances can share the work, publishes, and marks them in a second transaction.

Consumers must be idempotent by event id, because the relay is at-least-once. Trade-offs: the outbox table grows and needs a deletion job; polling adds latency and load; CDC adds operational surface.

What I would not do: publish from a TransactionSynchronization.afterCommit callback and call it "reliable" — if the process dies between commit and publish, the event is lost, which is exactly the gap the outbox exists to close. A2 covers the delivery-guarantee side.

Land it The outbox turns "publish exactly once" into "insert a row in the same transaction", which is the only atomicity the database can promise you.

Likely follow-ups
"Requirement change: events for one order must be delivered in order. What changes?"

Two things.

The relay must publish events for the same aggregate to the same Kafka partition, so I key the message by aggregate_id, and it must publish them in creation order, so the polling query orders by the UUID v7 id or a sequence within the aggregate, and a single relay instance owns a given partition of outbox rows at a time.

With several relay pods using SKIP LOCKED, two pods can pick up two events for the same order and publish them out of order, so I either partition the outbox by a hash of aggregate_id and assign hash ranges to pods, or accept a single active relay with a standby.

Debezium handles this naturally because it reads the WAL in commit order and its outbox event router keys by aggregate id.

"The relay published the event but crashed before marking the row. What happens, and is that acceptable?"

The row is still unpublished, so the next poll republishes it, and the consumer sees the same event twice.

That is the at-least-once guarantee, and it is acceptable only because the consumer is idempotent: it records the event id in its own processed-events table in the same transaction as its side effect, and skips duplicates.

If consumers cannot be idempotent, Kafka's idempotent producer and transactions can deduplicate within the producer's session, but not across a relay restart, so the outbox row id must still be the deduplication key downstream.

The check I run in staging is killing the relay pod mid-batch and asserting that every event was delivered and every consumer side effect happened exactly once.

"What would you cut under time pressure?"

I would cut Debezium and ship the polling relay: a @Scheduled method every 200 milliseconds, a select ... where published_at is null order by id limit 100 for update skip locked in a short transaction, publish with KafkaTemplate.send().get() per row, then set published_at.

It is fifty lines and needs no new infrastructure. I would also cut the cleanup job and simply partition or index on published_at so the poll stays fast, and add cleanup later.

What I would not cut is writing the outbox row in the same transaction as the order change, and the consumer's idempotency table, because those are the two pieces that make it correct rather than merely fast.

"How does this look with Spring Modulith or Spring's event publication registry?"

Spring Modulith's event publication registry, available since 1.0 and stable as of Aug 2026, is an outbox for in-process listeners: publishing an application event inside a transaction writes an event_publication row in the same transaction, the @ApplicationModuleListener runs after commit on another thread, and the row is marked completed when it finishes; incomplete rows are resubmitted on restart.

To reach Kafka, its externalisation support (@Externalized) publishes the event to a topic from that listener. It gives me the same-transaction write and the retry loop for free, in exchange for tying the outbox to Spring's event model and to a single application.

For a service that owns its Kafka contract, I would still write the explicit table.

Q31 · Scenario. "An @Async method receives an Order entity from a controller and tries to read order.getLines(). It fails intermittently — sometimes with LazyInitializationException, sometimes with stale data. Explain both symptoms."

Reveal answer

Strong answer Symptom one: the exception.

The entity was loaded on the request thread's persistence context; the async method runs on a different thread with no bound context, so a lazy collection has no session and throws — unless the request thread's session happens to still be open (OSIV) at the moment the async thread touches it, in which case it works, which is the intermittency.

Symptom two: stale data.

When it does work, the collection loads through the request thread's session from another thread, which is not thread-safe; and if the request transaction has not committed yet, the async thread may read through a session mid-flush or see a state that is later rolled back.

Evidence: correlate failures with request duration — short requests close the session before the async thread runs; long ones leave it open.

Fix: pass the order id to the async method, and have it open its own @Transactional boundary and reload the entity; schedule the async work from a TransactionSynchronization.afterCommit hook so it only sees committed state.

Prevention: a rule that entities never cross a thread boundary — ids and DTOs do.

Land it A session belongs to one thread and one transaction; hand another thread an id and let it open its own.

Likely follow-ups
"They changed the @Async method to take the order id and reload it, and it now sometimes gets 'not found'. Why?"

Because the async method started before the request's transaction committed.

@Async hands the call to an executor immediately, so the new thread opens its own transaction and reads under READ COMMITTED; if the order INSERT has not committed yet, the row is invisible and findById returns empty.

The fix is to schedule the async work from TransactionSynchronization.afterCommit, or to publish an application event and mark the listener @TransactionalEventListener(phase = AFTER_COMMIT) combined with @Async, so the hand-off happens only after the commit.

The intermittency matches request timing exactly: fast commits win the race, slow ones lose it. A test with an artificial sleep before commit reproduces it deterministically.

"What does the thread-safety problem look like in practice — how would you see it?"

Two threads driving one Session corrupt its internal state: the classic symptoms are ConcurrentModificationException from inside StatefulPersistenceContext or the action queue, IllegalStateException: Session/EntityManager is closed thrown on the async thread when the request thread commits mid-load, and connection errors like "This connection has been closed" because Hibernate released the JDBC connection under the other thread.

Less visibly, a collection initialised on the wrong thread can be half-populated. Hibernate does not detect it, and as of Aug 2026 there is no built-in guard.

The diagnosis is a thread dump or a log with thread names showing two threads with frames inside the same session instance, or simply the rule that any entity crossing a thread boundary is a bug.

"What if the async work needs the lines exactly as they were at request time, not as they are later?"

Then pass a snapshot, not an entity. Build an immutable record inside the request transaction — the order id, the status, a list of line records — and hand that to the async method.

It has no proxies, no session, and no way to be stale relative to what the request saw, and the async method does not need a transaction at all unless it writes.

If the snapshot is large, write it to the outbox or to a job table in the request transaction and pass only the row id; the async worker then reads its own committed copy.

Serialising the entity to JSON before the hand-off is a tempting shortcut that initialises every lazy association on the request thread and ties the wire format to the mapping, so I avoid it.

"Does the same apply to CompletableFuture and reactive pipelines?"

Yes, more strictly. Anything that continues on another thread — CompletableFuture.supplyAsync, a parallel stream, an executor, a Reactor scheduler — loses the thread-bound EntityManager and the transaction.

A @Transactional method that returns a CompletableFuture commits when the method returns, not when the future completes, so any database work inside the future runs outside the transaction.

Reactor and WebFlux are worse, because Hibernate ORM is blocking and thread-bound by design; Hibernate Reactive exists for that world with its own session model.

The one exception is structured concurrency with virtual threads, where a scoped value could carry a context, but Spring's JpaTransactionManager still binds to ThreadLocal as of Aug 2026, so the rule stands: ids across threads, entities within one.

Q32. "How would you make a service method that must both update a row and send an email do the right thing on rollback, without an outbox?"

Reveal answer

Strong answer Register the side effect to run after commit, using Spring's transaction synchronisation.

Inside the @Transactional method, after changing the entity, call TransactionSynchronizationManager.registerSynchronization with an afterCommit implementation that sends the email — or, more cleanly, publish a Spring application event and annotate the listener with @TransactionalEventListener(phase = AFTER_COMMIT), which does the same registration for you.

If the transaction rolls back, the listener never runs, so no email describes a change that did not happen. Two caveats a senior should add.

First, afterCommit runs on the same thread with the transaction resources still bound but the transaction finished, so any repository call inside it runs in a new, separate transaction — and the default @TransactionalEventListener will not start one, so writes there are lost unless you add @Transactional(propagation = REQUIRES_NEW).

Second, this is best-effort, not reliable: a crash between commit and the email loses the email, which is acceptable for a notification and unacceptable for a payment event — that is the line where the outbox from Q30 becomes mandatory.

Land it AFTER_COMMIT listeners give you "never on rollback"; only an outbox gives you "always after commit".

Likely follow-ups
"Why are writes inside a default @TransactionalEventListener lost — what is the mechanism?"

In the AFTER_COMMIT phase the transaction has finished, but Spring still has the EntityManager and connection bound to the thread while it runs the synchronisations, and TransactionSynchronizationManager.isActualTransactionActive() reports true.

So a repository call inside the listener joins what looks like an active transaction, its persist goes into the still-open session, and then the session is closed and the connection returned without another commit — the change is never flushed. Nothing throws.

The remedy is @Transactional(propagation = REQUIRES_NEW) on the listener method, which suspends the finished resources and opens a real transaction. Spring documents this, and the puzzling part for most people is that REQUIRED does not help because Spring thinks a transaction already exists.

"What if the email service is slow — does afterCommit block the response?"

Yes, it runs synchronously on the request thread after commit, so a two-second SMTP call adds two seconds to the response while holding no database resources.

If that latency matters, combine the listener with @Async, which hands the send to an executor after the commit; the order of annotations does not matter, because Spring wraps the async proxy around the listener invocation.

The cost is losing the exception: a failed send is logged by the async exception handler and nobody retries it. That is fine for a courtesy email; for anything that must happen, the failure needs to be recorded somewhere durable, which brings back the outbox.

I would also set a timeout on the mail client, because an unbounded call on the request thread is still a thread leak.

"How would you test that the email is not sent on rollback?"

An integration test with a real transaction manager and a mocked mail sender. Run the service method inside a TransactionTemplate that throws after the change, or use a method that fails on a constraint violation at flush, and assert the mock was never called.

Then run the success path and assert it was called exactly once, after the commit — I check ordering by having the mock query the database in a separate connection and assert the row is visible, which fails if the listener ran BEFORE_COMMIT by mistake.

The test class must not be @Transactional, because a test-managed transaction that is rolled back at the end never commits, so AFTER_COMMIT listeners never fire and the test would pass for the wrong reason.

"What about the rollback side — can you run something only on rollback?"

Yes: @TransactionalEventListener(phase = AFTER_ROLLBACK) or the afterCompletion(status) method of a TransactionSynchronization, where status is STATUS_ROLLED_BACK. The use is compensation that lives outside the database — releasing a reservation held in Redis, cancelling a payment authorisation, or emitting a "failed" metric.

Note the case where the transaction was never active: by default @TransactionalEventListener methods do not run at all if the event was published outside a transaction, unless fallbackExecution = true is set, which is a common surprise in tests and in code called from a scheduled job without a transaction.

The AFTER_COMPLETION phase runs in both outcomes when you need cleanup either way.

Q33 · Design. "Design the unit-of-work boundaries for a checkout: reserve stock, create the order, charge the card, confirm. Where do the transactions start and end, and what is in each?"

Reveal answer

Strong answer Requirements: no card charged without an order, no stock reserved forever if the charge fails, no database transaction open during the payment gateway call, and idempotency when the client retries. Design in three short transactions.

Transaction one: load the products with PESSIMISTIC_WRITE (or an atomic UPDATE stock SET reserved = reserved + ? WHERE available >= ?), create the order in status PENDING_PAYMENT with an idempotency key from the client, and commit — a few milliseconds, holds locks briefly.

Outside any transaction: call the payment gateway with the order id as the idempotency key, so a retry cannot double-charge; this takes seconds and must hold no connection.

Transaction two: reload the order by id, apply markPaid() or markFailed(), release the reservation on failure, insert the outbox event, commit. A scheduled sweeper handles orders stuck in PENDING_PAYMENT longer than five minutes by querying the gateway and reconciling.

Trade-offs: the state machine and the sweeper are more code than one big transaction; the benefit is that pool occupancy is bounded by database time only, and every step is retryable.

What I would not do: one @Transactional around all four steps, which holds stock locks and a pool connection for the gateway's full latency and turns a gateway slowdown into a database outage — the E7 saga pattern is this design with the steps in different services.

Land it Transactions bracket database work only; the remote call sits between two of them with an idempotency key on both sides.

Likely follow-ups
"Requirement change: the payment gateway supports a two-step authorise-then-capture. Where do the boundaries move?"

The shape stays the same and gains one state. Transaction one reserves stock and creates the order in PENDING_AUTH. Outside any transaction, authorise the card with the order id as the idempotency key.

Transaction two records the authorisation id and moves the order to AUTHORISED, still holding the reservation.

Capture happens when the order ships, which may be days later: a third short transaction marks CAPTURING, the capture call runs outside a transaction, and a fourth transaction records PAID and writes the outbox event.

The sweeper now also voids authorisations older than the gateway's hold window, typically seven days, for orders that never shipped.

Each remote call still sits between two short transactions with a state that says "in flight", so a crash anywhere is recoverable by looking at the state.

"What would you cut with a week to launch?"

The sweeper is the tempting cut, and it is the wrong one; without it a crash between the gateway call and transaction two leaves a charged card and a pending order forever.

I would keep the three transactions, the idempotency key, and a minimal sweeper that only alerts a human on orders stuck in PENDING_PAYMENT for more than ten minutes rather than reconciling automatically.

I would cut the stock reservation's own expiry logic by giving reservations a hard TTL enforced by the sweeper's same query, and cut the outbox in favour of an AFTER_COMMIT listener for the confirmation email only, since that is a notification, not a financial event.

The cuts must leave a system that is recoverable by hand, not one that silently loses money.

"The client retries the checkout call after a timeout. Walk me through what happens at each step."

The retry carries the same client idempotency key.

Transaction one tries to insert the order with that key in a unique column; if the first attempt already committed, the INSERT fails with a duplicate-key error, the service catches it, loads the existing order by key, and continues from its current state rather than creating a second order or reserving stock twice.

If the existing order is PENDING_PAYMENT, the service calls the gateway again with the order id as the gateway's idempotency key, and the gateway returns the original result rather than charging again.

Transaction two then applies that result, which is idempotent because markPaid() on an already paid order is a no-op. If the first attempt never committed transaction one, the retry simply proceeds as a first attempt. Every step is safe to repeat.

"Why not use a distributed transaction across the database and the gateway?"

Because the gateway is not a transactional resource — it has no prepare and commit protocol you can enlist in — so two-phase commit is not even available, and even where both sides are XA-capable, such as a database and a JMS broker, the coordinator holds locks across the prepare phase and becomes an availability and latency problem.

The industry answer is the pattern above: short local transactions, an idempotency key on every remote call, an explicit in-flight state, and a reconciler. That is a saga with a single participant.

When the steps live in different services, the same design becomes the saga from the microservices chapter, with the state machine kept in the orchestrating service and the outbox carrying the commands.

Q34. "What does Session.getManagedEntities() give you in Hibernate 7, and what would you use it for?"

Reveal answer

Strong answer Hibernate 7 added Session.getManagedEntities() — with an overload taking an entity class — returning a collection of every entity instance currently in the persistence context.

Before 7, seeing inside the context meant unwrapping to SharedSessionContractImplementor and walking the PersistenceContext SPI, which nobody did outside debugging. The practical uses are diagnostic and defensive.

Diagnostic: a batch job can log getManagedEntities().size() after each chunk to prove the flush-and-clear discipline holds, and an integration test can assert the context is empty at a boundary.

Defensive: a "safe clear" that detaches all entities of one type while keeping others, or a pre-flush check that no entity of a forbidden type — say, a read-model projection accidentally mapped as an entity — is managed in a write transaction.

Paired with getStatistics().getEntityCount() it separates "how many objects are managed" from "how many were loaded". It is not a way to iterate the database, and iterating it while modifying the context is unsafe, like any collection view.

Land it It is a window into the first-level cache — use it to measure and assert context size, not to do work.

Likely follow-ups
"How did you inspect the context before Hibernate 7?"

Through the SPI: session.unwrap(SharedSessionContractImplementor.class).getPersistenceContext(), then reentrantSafeEntityEntries() to iterate entity-and-entry pairs, or getNumberOfManagedEntities() for the count. It works in every 5.x and 6.x version but is internal, so it can change without notice and it is easy to break the context by mutating while iterating.

The other tools were Statistics.getEntityCount() — wrong name, it is loads not managed count — and heap dumps. Hibernate 6's hibernate.session.events.log can also print a summary at session close that includes entity counts.

For a Spring Boot 3.x service on Hibernate 6.6, which is still common as of Aug 2026, the SPI route is what I would wrap in a small utility for tests.

"Would you leave a getManagedEntities() check in production code?"

Behind a metric, yes; as a guard that throws, no. A gauge sampled at the end of batch chunks or on a slow-transaction hook that records the managed count tells you when a context grew unexpectedly, and it costs a map size lookup.

A check that throws when the count exceeds a threshold turns a performance concern into an outage.

The one production guard I would consider is an assertion in a shared batch utility that getManagedEntities().isEmpty() holds after clear(), because that catches the case where something re-attached entities between the flush and the clear.

In tests, the assertion is free and I would use it in every batch job's integration test.

"What else did Hibernate 7 change that a senior engineer should know?"

As of Aug 2026, the headline changes are: Jakarta Persistence 3.2 as the baseline, with find options, Timeout and lock options, and EntityManagerFactory.runInTransaction; JDK 17 minimum; @UuidGenerator version 7; @SoftDelete with a timestamp strategy; JSON and XML functions in HQL; StatelessSession.upsert and batching.

Jakarta Data repository support; the removal of long-deprecated APIs like Session.update and saveOrUpdate in 6, and of the legacy criteria API; stricter validation of temporal column types, which is the Q38 scenario; and the hibernate-jpamodelgen rename to hibernate-processor.

Spring Boot 4 ships Hibernate 7.1 and Spring Data JPA 4, so a Boot 3 to 4 upgrade is where most teams meet all of this at once.

"Is there a per-class size limit or eviction policy for the persistence context?"

No. The context is an unbounded map, and Hibernate never evicts on its own; it only shrinks on clear(), detach(), and close. That is by design, because evicting a managed entity behind your back would break the identity guarantee and lose unflushed changes.

So the only policies are the ones you apply: read-only loads to reduce the per-entity cost, projections to avoid entities entirely, and clear() at chunk boundaries. The second-level cache is the component with eviction and size limits, but it is a different structure.

If someone asks for "a bounded first-level cache", the answer is a bounded transaction.

Drill · Where the ORM meets the database

This group connects the persistence context to what the database is doing underneath — isolation, locks, and the connection — so you can answer the cross-cutting follow-ups.

Q35. "The persistence context gives repeatable reads within a transaction even on READ COMMITTED. Explain how, and where that illusion breaks."

Reveal answer

Strong answer On READ COMMITTED — PostgreSQL's default, discussed in E8 — each statement sees the latest committed data, so two SELECTs of the same row in one transaction can differ.

The persistence context hides that for entity loads: the first find() puts order 17 in the identity map, and a second find() returns the cached object without a statement, so your code sees the same values twice — application-level repeatable read.

Even a query that returns order 17 again hands you the managed instance and ignores the newer column values in the result set. The illusion breaks in four places. Projections and scalar queries bypass the identity map and always show current data.

A bulk JPQL update or native statement reads and writes the database directly. refresh() deliberately reloads. And it protects nothing about rows you have not loaded: a count or a sum runs against the current committed state.

So a transaction can hold an order whose total says 100 while the sum of its lines in the database, changed by another transaction, is 120 — consistent objects, inconsistent world.

Optimistic locking is what turns that into a detected conflict at commit rather than a silent overwrite.

Land it The identity map repeats objects, not the database's state — @Version is what makes the difference safe.

Likely follow-ups
"If you need a true consistent view, what do you set, and what does it cost?"

@Transactional(isolation = Isolation.REPEATABLE_READ), which Spring applies with Connection.setTransactionIsolation at begin and resets at the end.

On PostgreSQL that gives a snapshot of the whole database at the transaction's first statement, so counts, sums and projections agree with the entities you loaded, and a write to a row that changed since the snapshot fails with a serialization error that surfaces as CannotSerializeTransactionException, which you retry.

On MySQL, REPEATABLE READ is the default and gives consistent reads but does not abort writers, so lost updates remain possible without @Version or FOR UPDATE.

The cost is retries under contention and, on PostgreSQL, a slightly longer-lived snapshot; the JDBC driver also needs a round trip to set the level, unless the pool's default already matches.

"Does the second-level cache change any of this?"

It adds another layer with its own consistency rules.

A cached entity served from the second-level cache is at least as old as its cache entry, so in READ_WRITE or NONSTRICT_READ_WRITE mode a transaction on another node may see a value that the database has already changed.

Hibernate's TRANSACTIONAL strategy with a JTA-aware cache like Infinispan can keep it consistent, but most Spring Boot deployments cannot use it. Queries never use the entity cache unless the query cache is on, and even then the query cache holds ids that are re-resolved.

So the second-level cache can make the "consistent objects, inconsistent world" gap wider, which is why I limit it to reference data with TTLs and never put aggregates that are edited concurrently in it.

"How does a query with a join fetch behave when the entity is already managed and changed?"

The query runs, returns the joined rows, and for the root entity Hibernate hands back the managed instance with your in-memory changes, ignoring the fresh column values — unless the AUTO flush already wrote your changes, in which case the row and the object agree.

For the fetched collection it is subtler: if the collection was already initialised, Hibernate keeps the existing PersistentBag and its elements; if not, it initialises it from the result set.

So the parent shows your unflushed changes and the children show committed data, which is consistent only because the flush before the query usually happened.

If the flush was skipped — FlushModeType.COMMIT or a readOnly session — the mix is visible, and that is the case I test explicitly.

"Can you get 'repeatable read' for projections too, without changing isolation?"

Not from Hibernate. Projections are built fresh per query and never cached in the context, so the only way to make them stable within a transaction is the database's isolation or an explicit lock.

The pragmatic alternative is to fetch the projection once and pass the record around rather than re-querying, which is good practice anyway.

If a computed value like a total must match the entities you hold, compute it from the loaded entities instead of asking the database again, or lock the parent with PESSIMISTIC_READ so nothing changes underneath. Anything else is relying on timing.

This is the same reason I dislike "verify by re-query" patterns inside a transaction: the second query answers a different question than the first.

Q36 · Scenario. "Every request in a service holds a database connection for its entire duration, even requests that only call a remote API before touching the database. Hikari shows high active count. What setting is missing?"

Reveal answer

Strong answer Symptom: connections held from transaction start rather than from first statement. Evidence: Hikari active count tracking request count rather than database time, and thread dumps with a checked-out connection but no JDBC frame.

Cause: by default, when a transaction begins, Hibernate must ensure autocommit is off on the connection, and the only way to do that is to acquire the connection and call setAutoCommit(false) immediately — so the connection is borrowed at @Transactional entry, before any SQL, and held through the remote call.

Fix: configure the pool to hand out connections with autocommit already off — spring.datasource.hikari.auto-commit: false — and tell Hibernate that is the case with hibernate.connection.provider_disables_autocommit: true. Hibernate then skips the eager acquisition and borrows the connection at the first statement, releasing it after commit.

The same behaviour is described by the connection-handling mode DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION. Prevention: this pair belongs in every base configuration, alongside moving remote calls out of transactions entirely (Q18), because delayed acquisition only helps when the remote call comes before the first statement.

Land it Two properties turn "connection per transaction" into "connection per statement window" — set them, then still keep I/O out of transactions.

Likely follow-ups
"They set both properties and Hikari's active count barely moved. What next?"

Then the connection is acquired early for another reason. The most common one is the readOnly transaction path: older Spring versions fetched the connection at begin to call setReadOnly(true), so I check the Spring version and that LazyConnectionDataSourceProxy is not missing where routing is used.

The second is a datasource proxy, such as p6spy or datasource-proxy, or a multi-tenant connection provider that opens the connection itself.

The third is that the remote call is not before the first statement at all — the method reads something first, then calls the gateway — in which case delayed acquisition cannot help and the transaction must be split.

The proof is a breakpoint on HikariPool.getConnection with the stack showing who asked for it.

"Why does Hibernate need autocommit off at all?"

Because a JDBC connection in autocommit mode commits after every statement, which would make a multi-statement flush non-atomic.

The JDBC specification says a driver-level transaction begins implicitly with the first statement when autocommit is false, so Hibernate's begin() does nothing on the wire except make sure that flag is false.

Hikari can hand out connections with autocommit already false if you configure it, but Hibernate cannot know that unless you tell it, hence provider_disables_autocommit. With the flag set, Hibernate trusts the pool and skips the eager getConnection() plus setAutoCommit(false) pair.

It also skips restoring autocommit on release, which saves a round trip per transaction on drivers that send SET autocommit to the server.

"Does this work with the connection release mode after each statement?"

That mode, hibernate.connection.handling_mode=DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT, releases the connection after every statement and reacquires it for the next one, which is only meaningful with a JTA transaction manager that can hand back the same transactional connection.

With a plain DataSource and Hibernate's resource-local transactions, releasing mid-transaction would lose the uncommitted work, so Hibernate ignores the request and keeps the connection until commit.

The mode that applies to Spring Boot is DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION, which is the pair of properties from the answer. Hibernate logs a warning at startup if you configure a mode the transaction coordinator cannot honour.

"How would you quantify the benefit before rolling it out?"

Measure connection hold time per transaction before and after, using Hikari's hikaricp.connections.usage timer.

If the typical request spends 300 milliseconds in a remote call before its first statement and 20 milliseconds in database work, delayed acquisition cuts the hold time from 320 to 20 milliseconds, a sixteen-fold increase in the requests per second one connection can serve.

If the remote call comes after the first statement, the number does not move, and the metric tells you that honestly.

I would also watch hikaricp.connections.pending and the database's active session count, which should stay flat, and confirm in the SQL log that transactions still commit as a unit.

Q37. "How does Hibernate's optimistic lock interact with the database's isolation level? Do you still need @Version on SERIALIZABLE?"

Reveal answer

Strong answer They solve different windows.

Isolation governs conflicts between transactions that are open at the same time; SERIALIZABLE in PostgreSQL aborts one of two overlapping transactions whose reads and writes cannot be ordered, and REPEATABLE READ there aborts a writer whose row changed since its snapshot.

@Version governs a conflict across a window the database cannot see: the user loaded the order at 10:00 in one transaction, edited it in a browser for three minutes, and saved it at 10:03 in a second transaction.

To the database those are two unrelated, non-overlapping transactions; to the business it is one edit that must not overwrite the 10:01 change someone else made. Only the version column, carried through the detached state and checked in the UPDATE's WHERE clause, catches that.

So yes, you need @Version at every isolation level for any load-edit-save flow spanning transactions. Conversely, within a single transaction, @Version adds little on PostgreSQL REPEATABLE READ, and on MySQL REPEATABLE READ — where writers are not aborted — it is what prevents the lost update.

Pessimistic locks are the third tool, for the case where conflict is expected rather than rare.

Land it Isolation protects overlapping transactions; @Version protects the human-scale gap between two of them.

Likely follow-ups
"Give me a concrete lost-update sequence on MySQL REPEATABLE READ without @Version."

Transaction A loads order 17 with total 100 at time one. Transaction B loads the same row at time two, also sees 100. B sets total 120 and commits at time three.

A, whose snapshot still shows 100, sets total 110 and issues update orders set total = 110 where id = 17 at time four.

InnoDB's UPDATE reads the current row version, not the snapshot, so it succeeds — no error, no conflict — and B's 120 is gone.

With @Version, A's UPDATE carries and version = 1, B had bumped it to 2, the count is zero, and A gets OptimisticLockException.

On PostgreSQL REPEATABLE READ, A's UPDATE would fail with "could not serialize access due to concurrent update" even without a version, which is the difference the answer refers to.

"When would you choose SERIALIZABLE over optimistic locking?"

When the invariant spans multiple rows and cannot be expressed as one row's version.

The classic case is "no two on-call doctors can both go off duty": each transaction reads the count of on-duty doctors, sees two, and removes itself; both commit under REPEATABLE READ and the ward has none — a write skew.

No @Version on either row detects it, because neither row was modified by the other. PostgreSQL's SERIALIZABLE tracks read-write dependencies and aborts one transaction, which you retry. The cost is a retry loop on every transaction touching those tables and some CPU for predicate tracking.

The alternatives are a pessimistic lock on a parent row that represents the invariant, or a OPTIMISTIC_FORCE_INCREMENT on such a parent, which turns write skew into a version conflict.

"How would you verify that @Version is actually enforced in your service?"

A concurrency test: two threads, each in its own TransactionTemplate, both load order 17, a CountDownLatch ensures both have loaded before either commits, then both update a field and commit. Assert that exactly one throws ObjectOptimisticLockingFailureException and that the final row reflects only the winner.

That test also catches the detached-edit case if you simulate it by loading in one transaction, ending it, and saving in another after a competing write.

In production, Micrometer counts of that exception by entity type, exported from a @ControllerAdvice, show the check firing; zero conflicts on a busy aggregate is suspicious and usually means the version is not mapped on the path that writes.

"Does Hibernate ever set the isolation level itself?"

No. Hibernate uses whatever the connection has, which is the pool's default — spring.datasource.hikari.transaction-isolation if set, otherwise the driver's default, which is READ COMMITTED for PostgreSQL and REPEATABLE READ for MySQL.

Spring's @Transactional(isolation = ...) sets it per transaction through DataSourceUtils.prepareConnectionForTransaction and resets it on release, at the cost of a round trip each way on drivers that push the change to the server.

Hibernate's own property hibernate.connection.isolation exists but applies only when Hibernate manages the connection provider directly, which Spring Boot does not. So the honest answer is: the isolation level is a pool and Spring concern, and Hibernate's locking modes sit on top of it.

Q38 · Scenario. "After a Boot 3 to Boot 4 upgrade, the app fails at startup: 'Schema-validation: wrong column type encountered in column [created_at]; found [timestamp (Types#TIMESTAMP)], but expecting [timestamp(6) with time zone]'. What changed and what are the options?"

Reveal answer

Strong answer Symptom: ddl-auto: validate rejecting a timestamp column that Hibernate 6.6 accepted. Evidence: the column is mapped from an Instant or OffsetDateTime field, and the database column is a plain TIMESTAMP without time zone.

Cause: Hibernate 7 tightened the alignment between Java temporal types and SQL types — an Instant is a point on the timeline, so its faithful SQL type is TIMESTAMP WITH TIME ZONE, and validation now insists on it rather than tolerating the older implicit mapping.

Options, best first: a Flyway migration that alters the column to timestamptz — on PostgreSQL that is a rewrite of the table unless the session time zone is UTC, so run it with the expand-and-contract care from the primer on big tables; or keep the column and tell Hibernate the storage precision with hibernate.timezone.default_storage: NORMALIZE_UTC, which maps Instant to a plain timestamp normalised to UTC and satisfies validation; or, narrowest, annotate the field @Column(columnDefinition = "timestamp"), which pins the type but hides the mismatch.

Prevention: run the upgrade in a staging database with validate on, and read the Hibernate 7 migration guide's temporal section before touching production.

Land it Hibernate 7 stopped guessing about time zones — either the column says "with time zone" or you tell Hibernate how you normalise.

Likely follow-ups
"Which option would you pick for a 500 GB orders table, and how would you run the migration?"

The column change, but done carefully. On PostgreSQL, ALTER COLUMN created_at TYPE timestamptz rewrites the table unless the conversion is provably a no-op; since PostgreSQL 12, a timestamp to timestamptz change avoids the rewrite when the session's TimeZone is UTC, because the binary representation is identical.

So the migration sets SET timezone = 'UTC' first and runs the ALTER, which then takes an exclusive lock for milliseconds rather than hours.

I would still test it on a copy and set lock_timeout = '5s' so it fails fast rather than queueing behind a long query.

If the stored values were not UTC — a JVM in another zone wrote wall-clock time — the data needs an AT TIME ZONE correction first, and that is a rewrite by definition.

"The team chose NORMALIZE_UTC and now a different entity with OffsetDateTime shows the wrong offset. Why?"

Because hibernate.timezone.default_storage is global. NORMALIZE_UTC converts every OffsetDateTime and ZonedDateTime to UTC on write and stores no offset, so on read you get the same instant expressed with a zero offset — the original +05:30 is gone.

That is correct for instants and wrong for a field that must remember the customer's local offset, such as an appointment time.

The fix is per field: @TimeZoneStorage(TimeZoneStorageType.COLUMN) on that attribute, which adds a _tz column holding the offset, or NATIVE where the database supports a true timestamp-with-timezone type.

The global setting is for the common case; annotations carve out the exceptions, and the test is a round trip through the entity with a non-UTC offset.

"How would you find every column affected before the upgrade instead of discovering them one at a time?"

Run the new Hibernate version's schema validation against a copy of production in CI and collect all the failures at once — Hibernate stops at the first, so I would instead use hibernate.hbm2ddl.auto=none with the SchemaManager API from Jakarta Persistence 3.2, or generate the expected DDL with jakarta.persistence.schema-generation.scripts.action=create and diff it against pg_dump --schema-only.

A simpler approach is a query on information_schema.columns for timestamp without time zone columns, joined with a grep of entity fields typed Instant, OffsetDateTime or ZonedDateTime. Every match is a migration. That list also tells you which tables are big enough to need the lock-timeout treatment.

"What else in the Boot 3 to 4 upgrade tends to break at startup?"

As of Aug 2026, the usual suspects are: enum columns, where Hibernate 6.2+ adds CHECK constraints or expects native enum types on MySQL, so validation complains about a varchar that used to be fine; @Type annotations from Hibernate 5 that were removed and must become @JdbcTypeCode or a UserType; the sequence naming change from Q43 if it was never addressed; hibernate-jpamodelgen renamed to hibernate-processor, which breaks builds using the metamodel; Spring Data's getById removal in favour of getReferenceById; and stricter HQL parsing that rejects queries Hibernate 5 accepted. Running the full suite with ddl-auto=validate against Testcontainers on the new version, before touching production, finds most of them in one go.

Q39 · Design. "Design how a long-running report — 30 seconds, a million rows — reads through JPA without exhausting memory or holding a transaction that blocks VACUUM or replication."

Reveal answer

Strong answer Requirements: bounded heap regardless of row count, no persistence context growth, and a transaction short enough that PostgreSQL's VACUUM and a replica's replay are not held back — long-open snapshots pin old row versions across the whole database (see E8).

Design: a projection query into a record, not an entity, so no identity map or snapshot is involved; returned as a Stream<OrderSummary> from Spring Data with @QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "1000")) so the driver uses a server-side cursor — PostgreSQL requires the transaction to be open and autocommit off for cursors, MySQL needs useCursorFetch=true on the URL. Consume the stream in a try-with-resources inside a @Transactional(readOnly = true) method that writes directly to the response or a file, so memory is one fetch batch.

To keep the snapshot short, page by key instead of one cursor: where id > :lastId order by id limit 10000 in its own short transaction per page, at the cost of a few thousand more statements but no long-lived snapshot.

Trade-offs: cursor streaming is simplest but holds one transaction for 30 seconds; keyset pagination is fully restartable and replica-friendly.

What I would not do: findAll() into a list, or a Pageable with OFFSET, which rescans from the start on every page and issues a count query each time.

Going deeper Spring Data JPA has had first-class keyset pagination since 3.1, and as of Aug 2026 it is the tool I would name in the interview.

A repository method returning Window<OrderSummary> and taking a ScrollPosition — ScrollPosition.keyset() to start, then window.positionAt(window.size() - 1) for the next call — makes Spring generate the where (id) > (:last) order by id predicate from the sort you declare, including multi-column sorts, so you do not hand-write the tuple comparison.

Each call is its own short transaction, so no snapshot outlives a page.

Two mechanics matter for the cursor alternative: pgjdbc only uses a server-side cursor when fetchSize is positive and autocommit is off, so streaming outside a transaction silently loads the whole result set into memory; and MySQL Connector/J needs useCursorFetch=true on the URL, otherwise the only streaming mode is fetchSize = Integer.MIN_VALUE, which streams row by row.

The verification is a heap gauge during the report and pg_stat_activity showing the transaction's xact_start — for keyset paging it should never be more than a few seconds old.

Land it Project, stream or keyset-page, and keep each transaction shorter than the database's tolerance for an old snapshot.

Likely follow-ups
"Requirement change: the report must be a consistent snapshot as of its start time. Does keyset paging still work?"

Not on its own, because each page is a separate transaction that sees data committed since the previous page. Two options.

Run the whole export in one REPEATABLE_READ transaction with a server-side cursor, accepting a thirty-second snapshot — on PostgreSQL that is usually fine, since VACUUM is only held back for those thirty seconds and replicas only see a delay if hot_standby_feedback is on.

Or make the data itself versioned: page by key but filter on updated_at <= :reportStart and read from an append-only or audit table, so later changes are excluded regardless of when the page runs.

For a report that must be exact and is run rarely, the single cursor transaction is the simpler and more honest answer, and I would run it on a replica.

"What would you cut under time pressure?"

The keyset machinery.

A single @Transactional(readOnly = true) method returning a Stream from a projection query with a fetch-size hint of a thousand, consumed in try-with-resources and written straight to a gzip stream on the response, is twenty lines and handles a million rows in bounded memory.

I would run it against the read replica so its thirty-second snapshot cannot block VACUUM on the primary, and set statement_timeout at two minutes so a runaway cannot pin anything longer.

What I would not cut is the projection: returning entities from that query is the difference between a hundred megabytes of records and gigabytes of managed entities with snapshots, and it is one line in the query.

"Why does OFFSET pagination get slower, mechanically?"

OFFSET 900000 LIMIT 1000 tells the database to produce the first 901,000 rows in sort order and throw away 900,000 of them.

With an index on the sort key it walks 901,000 index entries and fetches their heap tuples; without one it sorts the whole table for every page. So page N costs proportional to N, and the total for all pages is quadratic.

Keyset pagination — where id > :lastId order by id limit 1000 — seeks directly to the last position in the index and reads a thousand entries, so every page costs the same.

Spring Data's Page also runs a count(*) per page by default; Slice avoids the count, and Window with keyset avoids both problems.

"How would you verify in production that memory really is bounded?"

Three signals. The JVM's old-generation usage during the report, from Micrometer's jvm.memory.used tagged by pool, should rise by one fetch batch and plateau, not climb with row count. Hibernate statistics should show getEntityLoadCount() unchanged, proving the projection did not create entities.

And on the database, pg_stat_activity during the run should show a single backend with a cursor-based FETCH or a series of short keyset queries, with backend_xmin — the oldest snapshot it holds — either short-lived or absent.

A load test that exports ten times the production volume with a heap capped at 512 MB is the cheapest way to make the claim before the first real run.

Q40 · Design. "A colleague proposes making every service method @Transactional by default with an aspect. Argue for or against, from the persistence context's point of view."

Reveal answer

Strong answer Against, with one concession. The concession: unmarked methods that call repositories get a session per repository call, so lazy loads after the call fail and two calls see two contexts — a default transaction would remove that whole class of bug.

The case against: a blanket transaction makes the persistence context's lifetime equal to the method's, and service methods do things transactions should not contain — remote calls, retries, sleeping on a queue, publishing events — so pool connections and row locks are held for the method's full duration (Q18, Q33), and a rollback on any runtime exception can undo work the method intended to keep.

It also makes every read path a writable transaction with snapshots and flushes unless the aspect distinguishes read-only methods by name, which is fragile.

Design instead: explicit @Transactional on the methods that own a unit of work, readOnly = true on queries, a linting rule (ArchUnit) that repositories are only called from transactional service methods, and open-in-view: false so the missing-transaction case fails in tests.

What I would not do: a global read-write transaction at the controller layer either, which is OSIV by another name.

Land it The transaction boundary is a design decision per unit of work, and an aspect that makes it universal makes every connection-holding mistake universal too.

Likely follow-ups
"Requirement change: the team has forty services with inconsistent boundaries and a week to reduce lazy-load bugs. Now what?"

Now I would take the aspect, with three constraints, as a temporary measure.

Apply it only to public methods of @Service classes whose name starts with get, find or list, and make those readOnly = true, so the blanket change costs no snapshots and no flushes; leave write methods alone and annotate them by hand as part of the same week.

Add an ArchUnit test that fails if a method inside a transaction calls a class in an HTTP client package, so the worst failure mode of blanket transactions is caught by the build.

And set an expiry: a ticket to remove the aspect once every service has explicit annotations. It buys a week of fewer bugs without committing to the design permanently.

"What would you cut if you could only enforce one rule?"

open-in-view: false everywhere, including tests. It is the single setting that turns "transaction boundary is wrong" into a test failure instead of a production surprise, because any lazy access after the service method throws.

Everything else — explicit annotations, readOnly on queries, the no-I/O rule — follows from developers seeing that exception during development and fixing the boundary at the right layer. The linting rules and the aspect are second-order.

If I had a second rule, it would be a query-count assertion in every service integration test, which catches the N+1 and the missing-transaction cases together, since both show up as a surprising number of statements.

"Isn't the repository's own @Transactional already a default transaction? Why is that not enough?"

It is a default per repository call, which is the wrong granularity. A service method that calls orderRepo.findById and then lineRepo.findByOrderId runs two transactions, so the order is detached by the time the lines arrive and the order's lazy collection cannot be touched.

Two calls also mean two identity maps, so the same customer loaded twice is two objects.

And a write that reads then saves runs the read in one transaction and the save in another, where save is a merge with a SELECT. The repository's transaction makes individual calls correct in isolation; the unit of work spans several calls, and only the service knows its extent.

That is why the boundary belongs on the service and the repository's annotation is a safety net.

"How do you explain to the team what belongs inside a transaction and what does not?"

With one sentence and one list. The sentence: a transaction is the shortest span that must succeed or fail together in the database, and nothing else.

The list of things that do not belong inside: HTTP calls, message publishing, waiting on futures, retries with sleeps, file I/O, cache writes that cannot roll back, and anything that takes longer than the database work itself.

The list of things that do: loading the aggregate, running its rules, writing it, writing the outbox row.

I would back it with the number from Q18 — each connection is a slot, and a two-second gateway call inside a transaction costs the pool two seconds of one slot — and with the leak-detection log line so people can see the offenders in their own code.

08 · DrillMapping, Ids, Relationships & Locking — Q41–Q80

Mapping questions look like annotation trivia and are graded as SQL prediction: can you say what statements a given mapping produces on save, on remove, on a collection change, and under concurrent edits? These forty questions cover id generation and its effect on batching, the owning side and cascade semantics, collection types, embeddables and inheritance, and both flavours of locking. Where MySQL and PostgreSQL differ, say which.

Drill · Id generation

This group tests whether you connect the id strategy to insert timing, batching, index shape and sharding — the four things it silently decides.

Q41. "Why does GenerationType.IDENTITY disable JDBC batching for inserts, mechanically?"

Reveal answer

Strong answer The persistence context is keyed by id, so an entity cannot become managed until Hibernate knows its id. With an identity column, the id is invented by the database during the INSERT and returned through getGeneratedKeys().

That forces Hibernate to execute the INSERT synchronously inside persist() — it cannot queue the statement for later, because the very next line of your code may put the entity in a map or set a foreign key that needs the id.

A JDBC batch is a list of statements sent together whose results come back together; since each identity INSERT must complete and return its key before the next entity can be handled, there is never a moment where two of them are pending at once.

So hibernate.jdbc.batch_size applies to UPDATEs and DELETEs of identity entities, but never to their INSERTs. Hibernate documents this explicitly and does not try to work around it.

On MySQL, where sequences do not exist, the choices are to accept it, to use rewriteBatchedStatements for the statements that can batch, or to generate ids in the application with time-ordered UUIDs.

why IDENTITY disables batchingruns offline
@Entity
public class Order {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)   // the problem
    private Long id;
}

// MECHANISM: with IDENTITY, the database assigns the id during the INSERT.
// Hibernate cannot know the id until the statement has EXECUTED. But an entity
// must have its id to be put in the persistence context, keyed by id.
// So persist() must execute the INSERT IMMEDIATELY, one statement at a time.
// JDBC batching is therefore impossible -- and Hibernate disables it silently.
// hibernate.jdbc.batch_size is present, correct, and completely ignored.

// FIX — a sequence, which Hibernate can read AHEAD of the inserts.
@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
    @SequenceGenerator(name = "order_seq", sequenceName = "order_seq",
                       allocationSize = 50)      // MUST match batch_size
    private Long id;
}
and the settings that make batching actually happenruns offline
spring.jpa.properties.hibernate.jdbc.batch_size = 50
spring.jpa.properties.hibernate.order_inserts   = true   # group same-table INSERTs
spring.jpa.properties.hibernate.order_updates   = true

# PostgreSQL: without this the driver still sends one statement per round trip,
# so Hibernate batches and the network does not.
spring.datasource.url = jdbc:postgresql://db/app?reWriteBatchedInserts=true

# VERIFY rather than assume:
spring.jpa.properties.hibernate.generate_statistics = true
# -> the log reports "X JDBC batches" -- if it says 200,000 batches for
#    200,000 rows, batching is off whatever the configuration says.

# ALSO REQUIRED, or the persistence context grows unbounded (see Q10):
#   em.flush(); em.clear();  every batch_size entities.

The allocationSize must match batch_size. If the sequence allocates 1 at a time, Hibernate makes a database round trip per id and the batching win is spent on sequence calls instead of inserts.

Land it Identity ids exist only after the INSERT, and the context needs the id before — so each insert is its own round trip.

Likely follow-ups
"Could Hibernate not batch identity inserts anyway and read the keys back from the batch?"

Technically the JDBC API allows getGeneratedKeys() after executeBatch(), and pgjdbc and Connector/J both return the keys, so it is possible in principle.

Hibernate does not do it because the persistence context contract requires the entity to be managed — and therefore keyed — immediately after persist() returns; deferring the INSERT would mean a window where em.contains(entity) is true but the entity has no key for the map, and every identity-map lookup and cascade would need special handling.

Hibernate's maintainers decided that complexity was not worth it when sequences exist. As of Aug 2026, StatelessSession.insertMultiple() in Hibernate 7 is the pragmatic route for bulk identity inserts, because a stateless session has no context to keep consistent.

"What does rewriteBatchedStatements actually do on MySQL, and is it safe?"

It makes Connector/J rewrite a JDBC batch of identical INSERTs into one multi-row INSERT ... VALUES (...), (...), (...) statement, and a batch of UPDATEs into a single multi-statement packet separated by semicolons, cutting round trips dramatically — often a five to ten times gain on inserts.

It is safe for inserts and deletes. The historical concern was update counts: with rewritten multi-row INSERTs the driver could not report per-statement counts, which matters only for versioned data, and Hibernate's batch_versioned_data covers that for UPDATEs.

It also needs max_allowed_packet large enough for the rewritten statement. It does not help IDENTITY inserts through the persistence context, because those never reach a batch in the first place.

"How would you show a colleague the difference in numbers?"

A ten-line benchmark against Testcontainers PostgreSQL: persist ten thousand entities in a flush-and-clear loop of fifty, once with GenerationType.IDENTITY and once with SEQUENCE and allocationSize = 50, with hibernate.jdbc.batch_size=50 in both. Print Statistics.getPrepareStatementCount() and wall time.

Typical numbers on a local container: identity issues ten thousand statements in a few seconds; sequence issues about two hundred batched INSERTs plus two hundred sequence calls in well under a second.

Over a real network with a one-millisecond round trip the gap widens to ten seconds versus under half a second. The org.hibernate.engine.jdbc.batch logger at DEBUG shows "Executing batch size: 50" only in the second run.

"If a legacy MySQL schema must keep auto-increment ids, what do you do for a bulk import?"

Bypass the persistence context for that path.

Use StatelessSession with insert() — Hibernate 6.x and 7 batch stateless inserts when batch_size is set, and with rewriteBatchedStatements=true the driver turns them into multi-row statements even for auto-increment tables, because the stateless session does not need the keys back before the next insert.

Or use plain JdbcTemplate.batchUpdate with the same driver setting, or MySQL's LOAD DATA INFILE for the largest loads. Keep the entity mapping on IDENTITY for the normal request path, where a single insert per request does not care about batching.

The point is that the id strategy is a per-table decision and the import path can use a different tool than the transactional path.

Q42. "Explain allocationSize and the pooled optimizer. What happens if the Java setting and the database sequence's INCREMENT disagree?"

Reveal answer

Strong answer allocationSize = 50 tells Hibernate that one call to the sequence buys a block of 50 ids.

The pooled optimizer (Hibernate's default for sequences since version 5, and Hibernate 6 defaults the whole strategy to per-entity sequences with increment 50) treats the value returned by the sequence as the upper end of the block: a sequence returning 100 means ids 51 to 100 are yours, so a new node starting mid-way reads the next value and knows exactly which block it owns.

pooled-lo treats the value as the lower end instead. Either way the database sequence must be declared INCREMENT BY 50 so two nodes never receive overlapping blocks.

If they disagree: Hibernate validates at startup and refuses to boot with "The increment size of the [orders_seq] sequence is set to [50] in the entity mapping while the associated database sequence increment size is [1]" — unless hibernate.id.sequence.increment_size_mismatch_strategy is set to LOG or FIX, in which case Hibernate either logs or silently adopts the database's value and your batching quietly drops to one sequence call per row.

Gaps in ids after a restart are expected and harmless; sequential-looking ids were never a contract.

Land it allocationSize is a promise the database sequence must keep — declare INCREMENT BY the same number, and let startup validation prove it.

Likely follow-ups
"Why is the pooled optimizer safe with several application nodes, mechanically?"

Because the database sequence is the only shared state, and each nextval is atomic.

With INCREMENT BY 50, node A calls the sequence and gets 100, so it owns 51 to 100 in memory with no further database contact; node B calls and gets 150, owning 101 to 150.

They cannot overlap because the sequence never returns the same value twice and each block is exactly the increment wide. A node that restarts abandons the rest of its block, which is the source of gaps.

Sequences on PostgreSQL are also non-transactional — a rolled-back transaction still consumed its value — so gaps appear from rollbacks too. What would break it is a database sequence with increment 1 and an application expecting 50, which is why Hibernate validates the pair at startup.

"What is the difference between pooled and pooled-lo, and which does Hibernate 6 use?"

Both hand out blocks of allocationSize; they differ in how they interpret the value returned by the sequence. pooled treats it as the high end of the block, so a sequence value of 100 means 51 to 100.

pooled-lo treats it as the low end, so 100 means 100 to 149.

The practical difference shows when a non-Hibernate writer uses the same sequence: with pooled-lo, another application calling nextval once gets 150 and Hibernate's block ends at 149, so the two coexist; with pooled, the sequence value 100 is the last id in Hibernate's block, and an outsider who took 100 collides.

Hibernate 5 and 6 default to pooled; hibernate.id.optimizer.pooled.preferred=pooled-lo switches it, and I set that whenever a sequence is shared with plain SQL.

"Would you ever set allocationSize to 1?"

Only for tables where inserts are rare and contiguity matters to a human — an invoice number that auditors expect to be gap-free, though even then a sequence does not guarantee it after a rollback, and the proper design is a separate gapless counter assigned at finalisation under a lock.

For everything else, size 1 costs one round trip per insert for the sequence call, which is the same cost as IDENTITY, and gives up batching for no benefit. A value between 20 and 100 is the normal range.

I would also avoid very large values like 10,000 in a system with frequent restarts, because each restart wastes the remainder and a BIGINT that "runs out" is not the worry — a confusingly sparse id space that people misread as data loss is.

"How would you migrate a live table from allocationSize 1 to 50 without downtime?"

Change the sequence first, then the code. ALTER SEQUENCE orders_seq INCREMENT BY 50 is instant and takes no table lock; running application instances with allocationSize = 1 keep calling nextval and simply get values fifty apart, which is harmless.

Then deploy the code with @SequenceGenerator(allocationSize = 50); new instances validate against the sequence and pass, and they allocate blocks below the value they receive, which cannot collide with the old instances because those only ever use the exact values the sequence returns.

The reverse order — code first — fails at startup with the increment mismatch error. If the strategy is set to FIX, Hibernate would alter the sequence itself, but I prefer the migration to be an explicit Flyway step.

Q43 · Scenario. "After a Hibernate 5 to 6 upgrade, the app fails on startup with 'Sequence orders_seq not found' although the schema has hibernate_sequence. What happened and what are the options?"

Reveal answer

Strong answer Symptom: schema validation asks for a sequence the migrations never created. Evidence: the entity uses @GeneratedValue(strategy = SEQUENCE) with no named generator, or plain @GeneratedValue under GenerationType.AUTO.

Cause: Hibernate 5 mapped both to one global hibernate_sequence with increment 1; Hibernate 6 changed the default to a sequence per entity named <table>_seq with increment 50.

Options: one, the clean fix — a migration that creates orders_seq, order_line_seq and so on with INCREMENT BY 50, started above the current maximum id, and entity mappings that name them explicitly with @SequenceGenerator(allocationSize = 50); two, the compatibility switch — hibernate.id.db_structure_naming_strategy: legacy (Hibernate 6 provides single and legacy strategies) to keep using hibernate_sequence, at the cost of a global contention point and increment 1, which means no batching gain; three, map @SequenceGenerator(sequenceName = "hibernate_sequence", allocationSize = 1) per entity as a bridge.

Prevention: name every generator explicitly in the mapping so upgrades cannot change your schema expectations, and run validate in a staging environment on the new version before production.

Land it Hibernate 6 changed the default sequence name and increment — explicit generator names are the only upgrade-proof mapping.

Likely follow-ups
"They created orders_seq with INCREMENT BY 50 but forgot to start it above max(id). What happens?"

Duplicate key violations on insert, once the new sequence's values reach existing ids.

If the table has ids up to 8,000,000 and the sequence starts at 1, the first block is 1 to 50, and the first INSERT fails with a primary key conflict; if the ids are sparse the failures are intermittent, which is worse because it looks like a concurrency bug.

The migration needs START WITH set to a value safely above the maximum: select setval('orders_seq', (select coalesce(max(id), 0) + 1000 from orders)) in the same Flyway script, with a margin for rows inserted between reading the maximum and switching over.

If it already happened, fix it with the same setval and let the application recover; nothing was corrupted, only rejected.

"Why did Hibernate 6 change the default, given the upgrade pain?"

Two reasons. A single global hibernate_sequence is a contention point: every insert of every entity type across every node hits the same sequence, and on PostgreSQL that is a lightweight lock but still one hot object; per-table sequences spread it out.

And increment 1 made the default configuration incapable of batching, so most teams had a mysteriously slow default and only the experienced ones knew to add allocationSize. Hibernate 6 chose the configuration that experts were already applying, at the cost of breaking implicit mappings.

The migration guide is explicit about it, and the lesson I draw is the one in the answer: never rely on an implicit generator name, because defaults are the one thing a major version is allowed to change.

"What does the legacy naming strategy setting actually do, and would you leave it on?"

hibernate.id.db_structure_naming_strategy=legacy restores the Hibernate 5 behaviour where @GeneratedValue(strategy = SEQUENCE) without a generator name uses hibernate_sequence, and single uses one shared sequence with the standard name. It changes only the implicit name; the implicit increment in Hibernate 6 is still 50, so even with legacy you get the increment mismatch error unless the old sequence is altered or allocationSize = 1 is declared. I would leave it on only as a bridge during the upgrade week, then name every generator explicitly and remove it, because a global setting whose meaning depends on the Hibernate version is a trap for the next upgrade.

"How would you catch this class of change before it reaches an environment?"

Run spring.jpa.hibernate.ddl-auto=validate in the CI integration tests against a Testcontainers database that Flyway migrated, so the schema Hibernate expects is compared with the schema the migrations produce on every build.

That catches sequences, column types, and the enum and timestamp changes from Q38 the day someone bumps the Hibernate version in the build file.

I would also generate the DDL Hibernate would create — jakarta.persistence.schema-generation.scripts.action=create to a file — and keep it in the repository, so a version bump shows up as a diff in the pull request.

Both are cheap and both make "the framework changed a default" visible before anyone deploys.

Q44. "Random UUID versus time-ordered UUID as a primary key — what does the difference do to the B+tree, and how much does it matter?"

Reveal answer

Strong answer A primary key index is a B+tree ordered by key value (E8 explains the structure).

With a sequence or a time-ordered key, every new row has a larger key than the previous one, so inserts always land in the right-most leaf page: that page stays hot in the buffer cache, splits happen predictably at the end, and the tree stays compact.

With a random version-4 UUID, each insert lands on a random leaf among millions, so every insert may need a page read from disk, causes splits in the middle of the tree that leave pages half full, and evicts useful pages from the cache.

On InnoDB the damage is doubled because the table is the primary-key index — rows are physically stored in key order — and every secondary index carries the 16-byte key too.

The magnitude: on a table of a hundred million rows the insert rate with random UUIDs can be several times lower and the index 30 to 50 percent larger.

Time-ordered UUID version 7, which Hibernate 7 generates natively, has the first 48 bits as a millisecond timestamp, so keys generated close in time sort close together and behave like a sequence while remaining globally unique and client-generated.

Store as native uuid or BINARY(16); a CHAR(36) doubles the size again.

Land it The key's ordering decides where inserts land in the tree — v7 gives you client-side generation without paying random-insert fragmentation.

Likely follow-ups
"How do you generate a version-7 UUID in Hibernate 6.6 versus 7?"

In Hibernate 7, @Id @GeneratedValue @UuidGenerator(style = UuidGenerator.Style.VERSION_7) does it natively, and as of Aug 2026 that is the version Spring Boot 4 ships. In Hibernate 6.6, the built-in styles are RANDOM, TIME — a version-1 style that is not the same thing — and AUTO; there is no version-7 style, so you either assign the id in the entity constructor from a library such as com.github.f4b6a3:uuid-creator with UuidCreator.getTimeOrderedEpoch(), or write a small IdentifierGenerator and attach it with @IdGeneratorType. Constructor assignment is simplest but breaks Spring Data's isNew, which brings back the Persistable pattern from Q22; the custom generator keeps the id null until persist and avoids that.

"Is UUID v7 standardised, and can two nodes generate the same value?"

It is: RFC 9562, published in May 2024, defines versions 6, 7 and 8 and obsoletes RFC 4122.

Version 7 is 48 bits of Unix milliseconds, then 12 bits the implementation may use for sub-millisecond ordering or a counter, then 62 bits of randomness after the variant bits.

Two nodes generating in the same millisecond differ in those 74 random or counter bits, so a collision is as unlikely as with version 4 — the timestamp prefix does not reduce uniqueness, it only orders.

Within one node, a good generator uses a monotonic counter in the 12-bit field so ids in the same millisecond still sort in creation order.

What it does not give you is a shard id or a strict global order across nodes, which is where the Snowflake design from Q45 comes in.

"What does the choice do to secondary indexes and joins, beyond the primary key?"

Every foreign key column that references the table carries the same 16 bytes, and every index on those foreign keys — which you need for joins and cascades — is twice the size of a BIGINT equivalent.

On InnoDB every secondary index also stores the primary key as its row pointer, so a table with five secondary indexes stores the UUID six times per row. Joins compare 16-byte values instead of 8, which is a small CPU cost.

The random-versus-ordered question affects secondary indexes less, because a secondary index on customer_id is ordered by customer, not by the row's primary key.

So the honest summary is: UUIDs cost about double the index space regardless of version, and version 7 removes the fragmentation penalty but not the size penalty.

"How would you measure the fragmentation claim on a real table?"

On PostgreSQL, the pgstattuple extension's pgstatindex('orders_pkey') reports avg_leaf_density and leaf_fragmentation; a sequence-keyed index sits around 90 percent density, a random-UUID index around 50 to 70 percent after sustained inserts. pg_stat_user_indexes and buffer-cache hit ratios from pg_statio_user_indexes show the cache misses per insert.

On MySQL, SHOW TABLE STATUS gives Data_free, and information_schema.INNODB_BUFFER_PAGE shows how much of the buffer pool the primary index occupies.

The controlled experiment is two identical tables filled with a million rows through the same code path, comparing insert throughput and index size; that is an afternoon's work and ends the argument with numbers.

Q45 · Design. "Design id generation for an orders service that is sharded across four regional PostgreSQL clusters and must merge data into one analytics store."

Reveal answer

Strong answer Requirements: ids unique across all shards without coordination, generated before the row exists so the application can reference them in events and outbox rows, roughly time-sortable so the analytics store and B+trees behave, and the shard identifiable from the id for routing.

Design: 64-bit ids in the Snowflake style — 41 bits of millisecond timestamp, 6 bits of shard or region, 10 bits of node, 6 bits of per-millisecond sequence — generated in the application by a small IdentifierGenerator implementation plugged in with @GeneratedValue(generator = "snowflake") and @GenericGenerator (or Hibernate 6.5+'s @IdGeneratorType meta-annotation), with the node id assigned from the pod's ordinal in a StatefulSet or leased from a small table at startup.

The result fits a BIGINT, sorts by time, batches like a sequence because the id is assigned at persist time, and routes by extracting the shard bits.

Alternative: UUID version 7 in a native uuid column — simpler, no node coordination, at the cost of 16 bytes per key and no embedded shard id.

Trade-offs: Snowflake ids depend on reasonably synchronised clocks and a unique node id, and a clock going backwards must be handled by waiting, not by generating; UUIDs need no clock discipline but double the index size.

What I would not do: per-shard sequences with offset ranges (shard one starts at 1, shard two at 1012), because ranges get exhausted or overlap after a resharding, and the ids carry no time ordering.

Land it Client-generated, time-ordered, 64-bit if you can and 128-bit UUID v7 if you would rather not manage node ids — never a database-coordinated sequence across shards.

Likely follow-ups
"Requirement change: the analytics store needs to know which region wrote each row, and ids are already UUID v7. Do you re-key?"

No. Re-keying a live sharded system is months of risk for a property you can add as a column. I would add a region column, two characters, populated by a default per cluster — PostgreSQL ALTER TABLE ... ADD COLUMN region text DEFAULT 'eu' is metadata-only since version 11 — and include it in the analytics extract.

The unique key across the merged store remains the UUID, which already cannot collide. If routing by id was the actual requirement, a lookup from id to region is a small table or a cache keyed by the customer, not something the id must encode.

The lesson is that embedding shard bits in the id is a nice-to-have when you design from scratch, and rarely worth retrofitting.

"What would you cut under time pressure?"

The Snowflake generator and node-id leasing. UUID v7 in a native uuid column is one annotation in Hibernate 7 and needs no clock coordination, no node ids, no StatefulSet ordinal, and no table to lease from.

The cost is the 16-byte key and no embedded shard id, both of which are acceptable for an orders service whose row counts are in the hundreds of millions, not billions.

I would keep the rule that ids are generated in the application before the INSERT, so outbox rows and events can reference them, and I would keep a region column for the analytics merge.

If the 64-bit requirement returns later — for a downstream system that cannot take UUIDs — a mapping table is the bridge.

"How do you handle the clock going backwards in a Snowflake generator?"

Detect and wait.

The generator keeps the last timestamp it used; if the current clock reads earlier, it either spins until the clock catches up, for small steps of a few milliseconds, or refuses to generate and raises an alert for large steps, because emitting an id with an older timestamp could collide with one already handed out in that millisecond and breaks the ordering guarantee.

Twitter's original implementation refused; many later ones wait up to a bounded time. Running the nodes with chrony in slew mode, which never steps the clock backwards, makes the case rare.

The alternative that avoids the problem entirely is using the sequence bits as a monotonic counter across milliseconds, as UUID v7 implementations do, at the cost of drifting slightly ahead of the wall clock under load.

"How does the analytics merge handle the same order being updated in two regions?"

It should not be possible, and the id design is what enforces it. Each order belongs to exactly one shard, chosen at creation by the customer's home region, and the shard bits in the id — or the region column — say which cluster is authoritative.

The analytics extract from each cluster is therefore disjoint by id, and the merge is a union, not a reconciliation.

If a customer moves regions, the order stays where it was created and new orders go to the new region; a migration of historical orders is a deliberate batch with the old row tombstoned.

What I would not do is allow writes to the same order from two clusters, because then the id design is irrelevant and you are building multi-master replication with conflict resolution, which is a different project.

Q46. "What is a natural id in Hibernate, how does @NaturalId change lookups, and when would you make it the primary key instead?"

Reveal answer

Strong answer A natural id is a business-meaningful unique key — an email, a SKU, an ISBN — as opposed to the surrogate id the database generates.

Marking a field @NaturalId makes Hibernate treat it as an alternate key: session.bySimpleNaturalId(Product.class).load("SKU-123") resolves the natural id to the primary key through a dedicated cache in the persistence context (and optionally the second-level cache with @NaturalIdCache), so repeated lookups by SKU inside a transaction hit the identity map like lookups by id, and Hibernate generates the unique constraint in the schema.

By default a natural id is immutable, and Hibernate throws if you change it, which is the right default for keys.

Making it the primary key instead — no surrogate — is right only when the natural key is genuinely immutable, compact and never reissued: an ISO country code, yes; an email address, no, because people change them and every foreign key would need updating; a SKU, usually no, because catalogues get merged.

The surrogate key keeps foreign keys small and stable while the natural id stays a unique constraint the application can look up efficiently.

Land it Surrogate primary key for stability, @NaturalId for the business key you actually look things up by.

Likely follow-ups
"How does a natural-id lookup differ from findBySku() in Spring Data, in SQL?"

findBySku("SKU-123") always runs select ... from product where sku = ?, and if the product is already managed it returns the managed instance after discarding the row.

session.bySimpleNaturalId(Product.class).load("SKU-123") first checks the persistence context's natural-id cross-reference — a map from natural id to primary key — and if the mapping is known, resolves through the identity map with no SQL at all; on a miss it runs a query for the id, then a load by id, which is two statements the first time unless Hibernate can combine them.

So the natural-id API wins for repeated lookups within a transaction and for entities held in the second-level cache with @NaturalIdCache; for a single lookup per request the Spring Data query is equivalent and simpler.

Hibernate also keeps the cross-reference up to date on flush, which a plain query cannot.

"What happens if a natural id has to change — a customer changes their email?"

By default Hibernate throws at flush: "An immutable natural identifier of entity Customer was altered". If the business allows the change, declare @NaturalId(mutable = true); Hibernate then re-synchronises the cross-reference on flush and still enforces uniqueness through the database constraint.

The cost is that the natural-id cache entry must be invalidated on change, which Hibernate does, and that the second-level natural-id cache becomes less useful.

My design preference for something like an email is not to make it a natural id at all but a plain unique column with a repository query, and to reserve @NaturalId for keys that are immutable by policy, such as a SKU, an ISBN or an account number, where the immutability check is a feature rather than an obstacle.

"How would you map a composite natural id, and how does the lookup change?"

Put @NaturalId on each of the participating fields — tenantId and orderNo, say — and Hibernate treats the combination as the natural key with a composite unique constraint. The simple-natural-id API no longer applies; you use session.byNaturalId(Order.class).using("tenantId", t).using("orderNo", n).load().

Everything else is the same: an in-context cross-reference, optional second-level caching, and immutability by default.

This is the mapping I use for the Q77 legacy composite-key situation when I can add a surrogate primary key: the surrogate becomes @Id, the old composite key becomes the natural id, foreign keys point at the surrogate, and the business still looks up by tenant and order number through an indexed unique constraint.

"When would you use the natural id as the primary key — walk me through the ISO country code case."

A country code is two characters, defined by an external standard, never reissued, and referenced from many tables.

Using it as the primary key means every foreign key is a readable two-character value, joins are unnecessary for display, and there is no surrogate to look up when importing data that already carries the code.

The risks a surrogate protects against — the key changing, being reused, or growing — do not apply. The same reasoning holds for currency codes, ISO language codes and similar reference data.

It stops holding for a SKU, because catalogues merge and SKUs get reassigned; for an email, because people change them; and for anything longer than a few bytes, because every index carries the key.

The rule is: natural primary key when the key is external, immutable, short and reference-like.

Drill · Relationships, ownership & collections

This group tests whether you can predict, for a given mapping, which side writes the foreign key and what SQL a collection change produces.

Q47. "What does mappedBy mean, mechanically, and what is the classic bug that comes from misunderstanding it?"

Reveal answer

Strong answer A relationship between two tables is one foreign key column in one of them.

When both Java classes reference each other, JPA must know which side's field corresponds to that physical column, because only one can be responsible for writing it; the other is a read-only view derived at load time.

mappedBy = "order" on Order.lines says "the column is owned by the field called order in OrderLine; I am the inverse side." At flush, Hibernate reads OrderLine.order to decide the value of order_id, and completely ignores the contents of Order.lines for that purpose.

The classic bug is adding a line to the parent's list and never setting line.setOrder(this): the in-memory graph looks right, the INSERT runs with order_id = NULL — or fails on a NOT NULL constraint — and the line is orphaned.

The same misunderstanding in reverse: removing a line from the list without nulling its order field does nothing, unless orphanRemoval is on. The fix is helper methods on the aggregate root that maintain both sides, and never exposing the mutable collection.

what mappedBy means, and the bug it causesruns offline
@Entity
public class Order {
    @OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();
}

@Entity
public class OrderLine {
    @ManyToOne @JoinColumn(name = "order_id")
    private Order order;            // <- THIS is the owning side
}

// mappedBy means: "I am the INVERSE side. The foreign key is managed by the
// field named `order` on the other entity. Hibernate does not read my
// collection to decide what to write to the order_id column."

// THE CLASSIC BUG — updating only the inverse side.
Order o = new Order();
OrderLine line = new OrderLine();
o.getLines().add(line);          // inverse side only
em.persist(o);
// INSERT into order_line ... order_id = NULL      <- or a not-null violation.
// Hibernate looked at line.order, found null, and wrote null.

// FIX — always set the OWNING side. A helper method makes it impossible to forget:
@Entity
public class Order {
    public void addLine(OrderLine line) {
        lines.add(line);          // keep the in-memory graph consistent
        line.setOrder(this);      // and set the side that actually persists
    }
    public void removeLine(OrderLine line) {
        lines.remove(line);
        line.setOrder(null);      // required for orphanRemoval to fire
    }
}

// Without mappedBy on a bidirectional pair you get TWO mappings for one column:
// Hibernate creates a join table, or issues a redundant UPDATE per row to set
// the foreign key after the INSERT.

The helper-method pattern is the answer to give. Bidirectional associations are only correct when both sides are maintained together, and the only reliable way to guarantee that is to make the mutation impossible to perform one-sidedly.

Land it mappedBy declares a mirror; the foreign key is written from the side holding @JoinColumn, and your helper methods must keep both in step.

Likely follow-ups
"Show me the helper methods, and explain why the collection must not be exposed."

On the root: public void addLine(OrderLine line) { lines.add(line); line.setOrder(this); } and public void removeLine(OrderLine line) { lines.remove(line); line.setOrder(null); }, with getLines() returning Collections.unmodifiableList(lines).

The add sets both sides so the INSERT carries the foreign key; the remove nulls the child's side so orphan removal fires and the in-memory graph has no dangling parent reference.

Exposing the mutable list lets a caller write order.getLines().add(line) without setting the back reference, which is exactly the bug in the answer. Returning an unmodifiable view makes that a runtime exception at the call site.

Hibernate still wraps the underlying field in a PersistentBag, because it uses field access, so the view does not interfere with lazy loading or dirty tracking.

"What happens if I set mappedBy on both sides by mistake, or on neither?"

Both sides with mappedBy: Hibernate fails at startup with "mappedBy reference an unknown target entity property" or, in Hibernate 6, an error that neither side owns the association, because there is no column to write.

Neither side with mappedBy: Hibernate sees two independent unidirectional associations — a @ManyToOne writing order_id on the child, and a @OneToMany that, having no @JoinColumn, creates a join table orders_order_line and writes into it.

The schema then has both a foreign key column and a join table, adds and removes double up, and the two views can disagree.

With ddl-auto=validate the extra table is caught; without it, the join table silently appears in a create or update environment and nobody notices until the statement counts look strange.

"Does the same bug happen with @ManyToMany?"

Yes, with a twist. In a many-to-many, the owning side is whichever entity declares @JoinTable, and only changes to that side's collection are written to the join table; changes to the mappedBy side are ignored entirely.

So tag.getProducts().add(product) on the inverse side writes nothing, and the developer sees the in-memory graph updated and the join table untouched.

The helper methods pattern applies, but I usually avoid the problem by not using @ManyToMany at all: mapping the join table as its own entity, ProductTag, with two @ManyToOne fields, makes the owning side unambiguous, allows extra columns like added_at, and turns removal into a single DELETE by id instead of the bag rewrite from Q48.

"How would you verify in a test that both sides are maintained?"

An integration test that adds a line through the helper, flushes and clears, then reloads the order by id and asserts lines.size() == 1 and lines.get(0).getOrder().getId() equals the order id.

The clear() is essential — without it the identity map returns the same in-memory graph and the test passes regardless of what was written.

I would also assert on the SQL: one INSERT into order_line with a non-null order_id, no follow-up UPDATE. For removal, remove through the helper, flush, and assert the row count in the child table dropped, which proves orphan removal fired.

These tests are five minutes each and they encode the aggregate's contract better than a comment.

Q48 · Scenario. "Removing one element from a @ManyToMany List on a product issues a DELETE of every join row followed by 29 INSERTs. Then under load, two edits to the same product deadlock. Diagnose."

Reveal answer

Strong answer Symptom one: a single removal rewrites the whole join table for that product. Evidence: the SQL log shows delete from product_tag where product_id=? then N-1 inserts.

Cause: a List without an @OrderColumn is a bag — an unordered collection that may contain duplicates — and Hibernate has no way to identify which row corresponds to which element, so on any change it deletes all rows and reinserts the current contents.

Symptom two: deadlocks.

Cause: two transactions editing the same product each delete the same set of join rows and reinsert; on InnoDB the deletes take gap locks and the reinserts wait on each other's gaps in opposite orders; on PostgreSQL the unique index on (product_id, tag_id) makes the second inserter wait on the first's uncommitted row while holding rows the first needs.

Fix: change the collection type to Set<Tag>, so Hibernate can address elements by value and the removal becomes one DELETE with both keys; or map the join table as an entity with its own id if it needs extra columns like added_at.

Prevention: a review rule that @ManyToMany and @OneToMany without an order column are Sets, and an @Version on the product so concurrent edits fail fast rather than lock.

Land it A List with no order column is a bag Hibernate must rewrite wholesale — Set is the one-word fix for both the statement storm and the deadlock.

Likely follow-ups
"They changed it to a Set and the deadlocks continue. What next?"

Then the statements are now minimal and the problem is acquisition order.

Two transactions editing the same product each touch product, product_tag and possibly tag rows, and if one starts by updating the product row while the other starts by inserting a join row, they can still lock in opposite order.

I read the deadlock report — PostgreSQL logs both statements, MySQL's SHOW ENGINE INNODB STATUS shows both waits — to see the two orders.

The fix is to lock the product row first in every path: findById(id, LockModeType.PESSIMISTIC_WRITE) or an OPTIMISTIC_FORCE_INCREMENT at the top of the edit, so concurrent edits serialise on one row before touching children.

If deadlocks still occur, they involve a table the report will name, and it is usually a foreign key to tag whose parent rows take shared locks.

"Why does a Set let Hibernate address a single row when a List cannot?"

A join row is identified by the pair (product_id, tag_id).

For a Set, Hibernate knows each element appears at most once, so the element's identity — its id, through equals and hashCode — maps to exactly one row, and a removal is delete from product_tag where product_id = ? and tag_id = ?.

A List without an order column may contain the same tag twice and has positions Hibernate cannot see in the table, so it cannot tell which row corresponds to which element and rewrites all of them.

A List with @OrderColumn is addressable by index and gets single-row statements too, at the cost of index shuffling on removal from the middle.

That is why the equals and hashCode discipline from Q6 matters here: a broken hash on Tag makes the Set unable to find the element, and the removal silently does nothing.

"Is @Version on the product the right answer to concurrent tag edits, or does it just move the failure?"

It moves the failure to a better place. Without it, two concurrent edits either deadlock or, with single-row statements, both succeed and interleave, which is usually acceptable for tags but wrong if the edit was "replace the tag set with this list".

With @Version, editing the product's tags does not by itself dirty the product row, so the version does not change — that is the Q65 point — and you need OPTIMISTIC_FORCE_INCREMENT on the load to make tag edits conflict.

Then the second editor gets a clean OptimisticLockException to retry, instead of a database deadlock victim chosen at random. Whether you want that strictness is a product decision; for additive operations like "add a tag" I would rather let both succeed and keep the single-row statements.

"How would you reproduce the deadlock in a test before the fix?"

Two threads, two TransactionTemplate transactions, a CyclicBarrier so both have loaded the same product before either flushes. Thread one removes tag A and calls flush(); thread two removes tag B and calls flush(); each then waits on a second barrier before committing.

With the bag mapping, both flushes issue delete from product_tag where product_id = ? followed by reinserts, and on Testcontainers PostgreSQL one of them fails with "deadlock detected" reliably, surfacing as Spring's CannotAcquireLockException.

After the change to a Set the same test passes, and the deadlock-victim assertion flips to asserting both commits succeed. Keeping that test in the suite is how the team stops the bag from creeping back in the next mapping.

Q49. "Unidirectional @OneToMany with @JoinColumn versus bidirectional with mappedBy: compare the SQL generated on adding a child."

Reveal answer

Strong answer Bidirectional with mappedBy: the child holds the foreign key, so adding a child is one INSERT into the child table carrying order_id. Clean.

Unidirectional @OneToMany with @JoinColumn(name = "order_id"), no back reference: the parent's collection is now the owning side, but the column lives in the child's table, and Hibernate handles that awkwardly — it INSERTs the child with order_id null (the child entity does not know its parent), then issues a separate UPDATE setting order_id from the parent's collection state.

Two statements per child, and the INSERT fails if the column is NOT NULL, unless the join column is declared nullable = false, in which case Hibernate includes the key in the INSERT but still issues the UPDATE on some paths.

Unidirectional without any @JoinColumn is worse: Hibernate creates a join table orders_order_line and adding a child is an INSERT into the child plus an INSERT into the join table, and removing one from a List deletes and reinserts the join rows like a bag.

So the ordering is clear: bidirectional with mappedBy for one-to-many collections; unidirectional is acceptable only for @ManyToOne on its own, which is the most efficient mapping of all — the child points at the parent and there is no collection at all.

Land it Put the @ManyToOne on the child, mappedBy on the parent, and skip the parent's collection entirely if you only ever query lines by order id.

Likely follow-ups
"When would you deliberately drop the parent's collection entirely?"

When the parent never needs to iterate its children as part of its own behaviour, and the children are numerous.

A customer with a hundred thousand orders should not have a List<Order>, because every operation that touches it — a cascade, a merge, a serialiser — risks loading a hundred thousand rows; the right access path is orderRepository.findByCustomerId(id, pageable).

The collection belongs on the parent only when the parent's invariants need it: an order needs its lines to compute a total and to enforce "no edits after shipping".

So the rule is that a @OneToMany collection is part of an aggregate's consistency boundary, and everything else is a query. Removing the collection also removes the bidirectional-maintenance bug class of Q47 entirely for that relationship.

"How does @OrderColumn change the SQL on add and remove?"

Adding to the end is one INSERT carrying the index in the line_no column.

Removing the last element is one DELETE. Removing from the middle of a list of N is one DELETE plus an UPDATE of the index for every element after it, so N minus the position updates — cheap for a ten-line order, expensive for a thousand-element list.

Inserting in the middle is similar. Compared to the bag it is strictly better, since a bag rewrites everything on any change; compared to a Set it costs the index maintenance but gives you stable positions, which matter for line numbers on an invoice.

Hibernate also requires the index column to be contiguous from zero; a gap from a manual delete causes null elements in the loaded list, which is a known trap.

"Does the bidirectional mapping have any cost the unidirectional one avoids?"

Two small ones. The child entity must carry a reference to the parent, which means loading a child creates a proxy for the parent — free unless touched — and serialising a child naively recurses into its parent and back, which is the Q78 stack overflow.

And the developer must maintain both sides, which is the Q47 bug class. Neither is a SQL cost; the bidirectional mapping produces the minimal statements.

The unidirectional @OneToMany with @JoinColumn avoids the back reference at the price of the extra UPDATE per child and the awkward null-then-set sequence.

If the goal is to avoid the back reference, the better trade is to keep only the @ManyToOne on the child and drop the parent's collection, which is unidirectional from the child's side and costs nothing.

"How would you check what a mapping generates without running the application?"

An integration test with spring.jpa.show-sql=false and logging.level.org.hibernate.SQL=DEBUG, plus the parameter binder logger, run against Testcontainers, captured through a ListAppender so the test can assert on statement shapes.

For the schema, jakarta.persistence.schema-generation.scripts.action=create writes the DDL Hibernate would generate to a file, which shows the surprise join table immediately. As of Aug 2026 Hibernate 7's SchemaManager API also exposes exportMappedObjects programmatically.

I keep one such "mapping contract" test per aggregate, asserting the exact statement count for add and remove, so a mapping change that alters the SQL fails in the pull request rather than in the SQL log of a production incident.

Q50. "Cascade REMOVE versus orphanRemoval — what is the difference, and give one mapping where each is wrong."

Reveal answer

Strong answer CascadeType.REMOVE says: when the parent is removed, remove the children too. It fires only on em.remove(parent).

orphanRemoval = true says: when a child is disconnected from the parent — removed from the collection, or the collection is replaced, or a one-to-one reference is set to null — delete that child, even though the parent lives on.

Orphan removal implies cascade remove as well.

Where cascade REMOVE is wrong: on any @ManyToOne or @ManyToMany, because the target is shared — cascading remove from an order line to its product deletes the product from the catalogue when the line is deleted, and on many-to-many it deletes rows other parents still reference, failing on a foreign key if you are lucky.

Where orphanRemoval is wrong: on a collection whose elements can be reassigned — moving a line item from one order to another by removing it from the first and adding to the second deletes it at flush, because it was orphaned from the first parent before Hibernate saw the second.

Both belong only on true composition, where the child cannot exist without exactly this parent: order lines, address of a customer, entries of an invoice.

Land it Cascade follows the parent's fate; orphanRemoval follows the link — use both only where the child has no life of its own.

Likely follow-ups
"How do you move a line from one order to another safely with orphanRemoval on?"

Do not remove it from the first collection. Orphan removal is evaluated at flush: if an element that was in the collection at load time is no longer there, it is scheduled for deletion, regardless of whether another parent now holds it.

So orderA.removeLine(line); orderB.addLine(line); deletes the row.

The safe options are to copy: create a new line on order B with the same data and remove the old one, which makes the history explicit; or to change the child's foreign key directly with line.setOrder(orderB) and, if the parent collections are held in memory, add and remove without orphan removal on that relationship.

If moving is a real operation in the domain, the mapping should say so by not having orphan removal, because orphan removal means "cannot exist elsewhere".

"Does replacing the collection instance trigger orphan removal or something worse?"

Something worse, historically. order.setLines(new ArrayList<>(newLines)) replaces Hibernate's PersistentBag with a plain list, and Hibernate throws "A collection with cascade=all-delete-orphan was no longer referenced by the owning entity instance", because it has lost the wrapper it was tracking and cannot compute the orphans.

The correct way to replace contents is order.getLines().clear(); order.getLines().addAll(newLines); on the existing collection, which orphan-removes what is gone and inserts what is new.

That exception is one reason to never expose a setter for a mapped collection, and to make the field final and initialised in the declaration — Hibernate sets it through reflection anyway.

"What does cascade REMOVE do to performance, and is there a set-based alternative?"

It loads every child and deletes it individually, which is the Q51 scenario: N SELECT-then-DELETE rounds, or N DELETEs batched if batch_size is set, plus callbacks and Envers entries per child. It is correct and observable but proportional to the children.

The set-based alternative is the database's ON DELETE CASCADE on the foreign key, declared to Hibernate with @OnDelete(action = OnDeleteAction.CASCADE) on the collection so Hibernate skips its own cascade and issues only the parent DELETE.

That is one statement, invisible to callbacks and auditing, and it also fires for deletes that bypass the ORM. I use the database cascade for true compositions with no per-child hooks, and the ORM cascade when something must observe each child going away.

"How would you verify that removing a line actually deletes the row, in a test?"

Load the order in a transaction, call removeLine(line), commit, and in a separate transaction — or through JdbcTemplate outside the context — assert that select count(*) from order_line where id = ? returns zero.

The separate read matters because inside the same context a stale collection could hide the outcome.

I also assert on the SQL log that exactly one DELETE with the line's id went out and no UPDATE set order_id to null, which is what happens when orphan removal is off and the developer expected it on.

And the negative test: removing a line from a shipped order throws before any SQL runs, which proves the invariant lives in the root method rather than in the mapping.

Q51 · Scenario. "Deleting an order with 2,000 lines takes 2,001 DELETE statements and four seconds. The team wants one statement. What are the options and their trade-offs?"

Reveal answer

Strong answer Symptom: cascade remove loads every child and deletes it individually.

Evidence: the SQL log shows a SELECT of the lines (cascade needs the entities to fire callbacks and maintain the context), then one DELETE per line, then the parent DELETE; each is a round trip because deletes batch only if batch_size is set and even then the load remains.

Options, ranked: one, a bulk JPQL delete from OrderLine l where l.order.id = :id via a @Modifying query, then delete the parent — two statements, no entity loading, but it bypasses callbacks, Envers auditing and the persistence context, so pair it with clearAutomatically; two, ON DELETE CASCADE on the foreign key in the migration, and @OnDelete(action = OnDeleteAction.CASCADE) on the mapping so Hibernate knows not to cascade itself — one statement, the database does the work, fastest, but invisible to any application-side hook; three, keep the cascade and enable JDBC batching with batch_size: 50, which turns 2,000 round trips into 40 but still loads the lines.

Trade-offs: bulk deletes are fast and blind; entity cascades are slow and observable. If auditing needs each line deletion recorded, the cost is the price of the requirement.

Prevention: soft delete (Hibernate 6.4+'s @SoftDelete) for aggregates that are "deleted" in the business sense but kept for history, which makes the operation one UPDATE.

2,001 DELETE statements, and how to get to oneruns offline
@OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true)
private List<OrderLine> lines;

repo.delete(order);
// SELECT the order
// SELECT the 2,000 lines            <- they must be loaded to be cascaded
// DELETE from order_line where id=? x 2000
// DELETE from orders where id=?

// WHY: cascade and orphanRemoval are JPA-LEVEL features. Hibernate must load
// each child entity so lifecycle callbacks and further cascades can run, then
// delete them one at a time. It is correct, and it is 2,001 round trips.

// FIX 1 — a bulk JPQL delete. Two statements.
@Modifying
@Query("delete from OrderLine l where l.order.id = :id")
void deleteLinesByOrderId(@Param("id") Long id);

@Transactional
public void deleteOrder(Long id) {
    lineRepo.deleteLinesByOrderId(id);      // 1 DELETE
    orderRepo.deleteById(id);               // 1 DELETE
}
// CAVEAT: a bulk delete BYPASSES the persistence context and the second-level
// cache. Any already-loaded OrderLine in this transaction is now stale, so
// call em.clear() afterwards, or do the bulk delete first.

// FIX 2 — let the DATABASE cascade, and tell Hibernate not to.
@OneToMany(mappedBy = "order")     // no cascade REMOVE, no orphanRemoval
private List<OrderLine> lines;
// with the schema: FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
// One DELETE, and the database does the rest. Fastest, and it also protects
// against orphans created by anything other than this application.

Fix 2 is the one worth arguing for on a large child table. The database enforces referential integrity anyway, so letting it do the cascade is both faster and more robust — at the cost of the deletion no longer firing JPA lifecycle callbacks, which matters only if you rely on them.

Land it Cascade remove is per-entity by design; if you want set-based deletion, say so in SQL and accept that no callback will see it.

Likely follow-ups
"They switched to the bulk JPQL delete and Envers now shows the order deleted but the lines still present. Fix?"

That is the blindness trade-off showing up: Envers records only what passes through the persistence context, so the bulk delete of lines left no order_line_AUD rows with REVTYPE = 2. Three fixes, in order of how much they cost.

Write the audit rows for the lines yourself in the same transaction — one bulk insert into order_line_AUD select ..., :rev, 2 from order_line where order_id = :id before the delete, which keeps the audit complete at the price of coupling to Envers' schema.

Or fall back to the entity cascade with JDBC batching for orders that are audited, and use the bulk path only for unaudited data. Or move line auditing to a database trigger, which sees every delete.

I would take the trigger for lines and keep Envers for the order header.

"Why is the four seconds so long for 2,000 deletes — what is the per-statement cost made of?"

Roughly two milliseconds per delete, which is mostly round trip and per-statement overhead, not the delete itself.

Each DELETE is a network round trip — a millisecond on a typical cloud network — plus statement parsing, plus the foreign-key check the database runs to see whether anything references the line, plus the index maintenance on every index of order_line.

If order_line has five indexes, that is five B-tree updates per row. And the initial SELECT that loaded the 2,000 lines added its own cost, including building 2,000 managed entities with snapshots. Batching removes the round trips: forty batches of fifty run in perhaps 200 milliseconds.

The single-statement delete removes the round trips and the entity loading, and lets the database delete the rows in one index pass, which is why it is tens of milliseconds.

"Which option would you choose for a soft-delete world instead, and what does the SQL become?"

With @SoftDelete on Order only, deleting the order becomes update orders set deleted = true where id = ?, one statement, and the lines are untouched; queries for lines through the order's collection stop returning them because the parent is filtered, but a direct query on order_line still finds them, which is usually what reporting wants.

If lines must also be hidden, put @SoftDelete on OrderLine too and the cascade issues one UPDATE per line — back to N statements, but batchable, and with no SELECT needed if Hibernate can cascade by the foreign key.

Hibernate 7's SoftDeleteType.TIMESTAMP records when instead of a boolean, which auditors prefer. The uniqueness question from Q75 applies to anything with a unique constraint.

"How would you verify the ON DELETE CASCADE option is safe before enabling it?"

Two checks. First, list every foreign key that points at order_line — select conname, conrelid::regclass from pg_constraint where confrelid = 'order_line'::regclass — because a database cascade on lines will either cascade further or be blocked by those, and each must be a deliberate decision.

Second, run the delete on a copy of production for the largest order and time it under EXPLAIN ANALYZE, checking that the foreign key columns on every dependent table are indexed; an unindexed foreign key turns the cascade into a sequential scan per parent row.

Then confirm Hibernate's mapping has @OnDelete so it does not also issue its own deletes, by asserting a single DELETE in the SQL log of the integration test.

Q52. "Why can a @OneToOne on the inverse side not be lazy, and what are the workarounds?"

Reveal answer

Strong answer A lazy to-one reference is implemented as a proxy that holds the foreign-key value and loads on first access.

On the owning side of a one-to-one, the foreign key column is in the entity's own row, so after loading a customer Hibernate knows the profile_id and can build a proxy — or set the field to null if the column is null.

On the inverse side (mappedBy), the foreign key lives in the other table: after loading the profile, Hibernate cannot tell whether a customer row points at it without querying the customer table.

A proxy would have to represent "maybe null", which a proxy cannot do — it is either an object or null. So Hibernate resolves the inverse side eagerly with an extra SELECT per load, whatever the fetch type says.

Workarounds: make the relationship unidirectional from the side that holds the key and query the other direction when needed; declare optional = false on the inverse side, which tells Hibernate a matching row always exists so a proxy is safe; use @MapsId so both entities share the same primary key and the "foreign key" is the id itself, which makes both directions proxyable; or enable bytecode enhancement with lazy-loading of no-proxy attributes.

In practice, shared primary keys via @MapsId is the mapping that removes the problem entirely.

Land it A proxy cannot stand in for "possibly absent" — put the key on the side you load from, or share the primary key with @MapsId.

Likely follow-ups
"What does the extra SELECT look like in practice, and how bad does it get in a list?"

Loading a Profile whose inverse @OneToOne(mappedBy = "profile") Customer customer is declared lazy produces select ... from profile where id = ? followed immediately by select ... from customer where profile_id = ?, because Hibernate must know whether to set the field to an object or to null.

In a list of a hundred profiles it is a hundred extra SELECTs — a classic N+1 that no FetchType.LAZY declaration can remove. The proof is the SQL log showing the customer query right after each profile load even though nothing touched getCustomer().

A join fetch of the customer in the list query removes it, at the cost of always loading the customer, which is often fine for a one-to-one.

"How does @MapsId make both directions lazy?"

With @MapsId, the Profile uses the customer's id as its own primary key: @Id Long id; @OneToOne @MapsId @JoinColumn(name = "id") Customer customer;.

Now the "foreign key" from profile to customer is the profile's own id, and from customer to profile it is again the same value.

So after loading a customer with id 42, Hibernate can build a proxy for the profile with id 42 without asking whether it exists — if there is no profile row, the proxy fails on initialisation with EntityNotFoundException, which is the one behavioural difference.

There is no separate profile_id column and no extra index. The trade is that a customer without a profile is represented by an absent row rather than a null column, and code that checks customer.getProfile() == null must change to a try or an exists query.

"What does optional = false actually promise, and what happens if the promise is broken?"

@OneToOne(mappedBy = "customer", optional = false, fetch = LAZY) tells Hibernate that every customer has a profile, so it can safely create a proxy without checking the other table — the proxy will be an object, never null.

If a customer row without a profile exists, the proxy initialises with a SELECT that finds nothing and throws EntityNotFoundException at the first access, which may be deep in a serialiser.

So the setting is a contract you must enforce with data: a NOT NULL, or in this case a guarantee that the child row is created in the same transaction as the parent.

I would add a periodic data check for customers without profiles, or better, create the profile in the customer's constructor path so the invariant is structural.

"Does bytecode enhancement fix it, and would you turn it on just for this?"

Enhancement with lazy initialisation enabled replaces the field-level proxy with an interceptor on the field itself: the customer's profile field is left unset until first access, and the access triggers the SELECT. Because there is no proxy object, "maybe null" is representable, so the inverse side can be genuinely lazy. It works, but I would not enable a build-time bytecode step across the whole codebase for one association; enhancement changes field-access semantics and has had subtle bugs with inheritance and embeddables in the 6.x line, though it is more stable as of Aug 2026. For a single one-to-one, @MapsId or dropping the inverse side is a mapping change with no build implications, and that is where I would start.

Q53. "@ElementCollection for a list of strings — what schema does it create, how does it update, and when would you replace it with an entity?"

Reveal answer

Strong answer @ElementCollection List<String> tags creates a separate table — by default product_tags with columns product_id and tags — whose rows have no identity of their own; they are values owned entirely by the parent, always cascaded, always orphan-removed.

Because the rows have no primary key, Hibernate treats the collection like a bag: any modification deletes every row for that parent and reinserts the current contents, exactly as in Q48, unless it is a Set (element-addressable) or has an @OrderColumn (index-addressable).

It is also always loaded with the parent's lifecycle and cannot be queried on its own — there is no entity to select.

Replace it with a real entity when any of these become true: the elements need to be queried independently ("all products with tag X" across the catalogue), referenced from elsewhere, given extra columns like a timestamp or an author, or paginated, or when the collection grows beyond a few dozen elements and the rewrite cost shows in the logs.

For a genuinely small, value-like set — a handful of alternate names, a few flags — the element collection is the honest mapping, and a JSON column (@JdbcTypeCode(SqlTypes.JSON)) is often better still.

Land it Element collections are values with bag semantics — promote to an entity the moment anything needs to find or reference them on their own.

Likely follow-ups
"Can you fetch an entity with its element collection in one query, and what does the result set look like?"

Yes, with select p from Product p left join fetch p.tags where p.id in :ids.

The result set is one row per product-tag pair, so a product with five tags occupies five rows and Hibernate de-duplicates the products by id as it builds the objects — since Hibernate 6 the distinct keyword is no longer needed for that.

The trap is fetching two collections in one query, tags and images: the rows multiply into a Cartesian product, five tags times four images is twenty rows per product, and for List collections Hibernate refuses with MultipleBagFetchException.

Two Set collections are allowed but still pay the product. The better tool is @BatchSize(size = 50) on the collection, which loads tags for fifty products in one where product_id in (...) query.

"How would you page over products and still show their tags efficiently?"

Not with a fetch join, because a fetch join with setMaxResults forces Hibernate to paginate in memory — it warns with "firstResult/maxResults specified with collection fetch; applying in memory" — and loads the whole table.

The right shape is two queries: page the products by id with a plain query, then load the tags for that page in one statement, either through @BatchSize on the collection, which Hibernate triggers automatically when you touch the first product's tags, or with an explicit select p from Product p left join fetch p.tags where p in :pageProducts.

Spring Data does this naturally if the page query is a projection and the tags are loaded by a second repository method. Hibernate 6's hibernate.query.fail_on_pagination_over_collection_fetch=true turns the warning into an exception so nobody ships it.

"What are the semantics of ordering — will the list come back in the order it was saved?"

Not unless you say so. A List element collection without @OrderColumn is stored as unordered rows and comes back in whatever order the database returns them, which is usually insertion order on a fresh table and arbitrary after updates and vacuum.

@OrderColumn(name = "position") stores an index and restores the exact list order, at the cost of index updates on removal. @OrderBy("value asc") on the field sorts at load time by a column value without storing a position, which is fine for tags that should be alphabetical.

For a Set, order is undefined by definition, and Hibernate uses a PersistentSet backed by a HashSet, or a LinkedHashSet if you declare @OrderBy. Tests that assert on list order without one of these annotations are flaky by design.

"When is the JSON column better than either the element collection or a child entity?"

When the values are read and written as a unit with the parent, are never queried individually across rows, and are small — a few dozen strings, a map of settings, a list of alternate names.

Then @JdbcTypeCode(SqlTypes.JSON) List<String> tags is one column in the parent row: no extra table, no join, no bag rewrite, one UPDATE on change, and the value is visible in the row for debugging.

It loses when the values need indexing per element — PostgreSQL's GIN index on jsonb covers containment queries like "products with tag X" reasonably well, but a real table with a B-tree wins for cardinality and joins — and when several writers update different elements concurrently, because the whole document is the unit of update and of the version check. The catalogue design in Q61 draws the same line.

Q54 · Design. "Design the entity model for orders with line items, shipping address snapshots, and the constraint that a shipped order's lines are immutable."

Reveal answer

Strong answer Requirements: an order is one consistency boundary — it and its lines change together; the shipping address must be frozen at order time because the customer's address may change later; lines of a shipped order must not be editable, enforced in both code and, ideally, the database; and the model must not make the common queries slow.

Design: Order as the aggregate root with sequence id and @Version; OrderLine as a child owning the order_id foreign key, with Order.lines as mappedBy, cascade = ALL, orphanRemoval = true, and an @OrderColumn so lines are addressable; a ShippingAddress record as an @Embeddable copied from the customer's address at creation, so it lives in the orders row and cannot drift; Product referenced by lazy @ManyToOne with no cascade and the unit price copied onto the line.

The immutability rule lives in the root: addLine and removeLine throw when status is SHIPPED, the collection getter returns an unmodifiable view, and a database trigger or a CHECK-style guard on order_line updates enforces it against non-ORM writers.

Trade-offs: copying address and price denormalises deliberately, trading storage for correct history; the ordered list costs line_no updates on removal.

What I would not do: a @ManyToOne from line to a shared Address entity, which would let a customer's address edit rewrite every historical order, and a @ManyToMany between orders and products, which loses quantity and price.

Land it Aggregate root, owning-side children, embedded snapshots for anything that must not drift, and invariants enforced in the root's methods — not in the controller.

Likely follow-ups
"Requirement change: an order can now be partially shipped, line by line. What changes in the model?"

The immutability rule moves from the order to the line. Each OrderLine gains a status — OPEN, SHIPPED, CANCELLED — and the root's changeQuantity(lineId, qty) and removeLine(lineId) check the line's status rather than the order's.

The order's own status becomes derived: PARTIALLY_SHIPPED when some lines are shipped, which I would compute in a method rather than store, or store and recompute in the same domain methods so it cannot drift.

Shipment becomes its own aggregate — a Shipment with ShipmentLine rows referencing order line ids by value, not by association — because shipments are created by a different process and should not lock the order.

The database guard becomes a trigger on order_line that rejects updates to shipped lines.

"What would you cut with a week?"

The database-side guard and the @OrderColumn. The trigger protecting shipped lines is valuable against non-ORM writers, but in week one the only writer is this service, so the root's method check is sufficient, and the trigger goes on the backlog with a date.

The order column costs index maintenance and a design decision about renumbering; a Set<OrderLine> with a line_no assigned by the root at add time gives stable numbers with simpler SQL.

I would keep the embedded address snapshot and the copied unit price without question, because retrofitting them means rewriting history, and I would keep @Version on the root, because adding it later requires a column backfill and a deploy that handles both states.

"Why an embeddable for the address rather than a separate address table with a snapshot row?"

Because the snapshot has no identity and no life outside this order.

An @Embeddable ShippingAddress — a record since Hibernate 6.2 — puts the five or six columns in the orders row: loading an order needs no join, the columns are constrained NOT NULL directly, and there is no id to cascade or orphan.

A separate order_address table would be a @OneToOne with all of Q52's lazy-loading problems for one extra row that is always needed.

The separate table wins only if the snapshot is large, optional for many orders, or shared with other aggregates such as invoices; then a @ManyToOne to an immutable address_snapshot row, deduplicated by content hash, saves space. For a typical shop the embeddable is the right size.

"How do you keep the copied unit price honest when the product price changes?"

By making the copy the source of truth for the order and never reading the product's current price for anything about that order. The line stores unit_price and currency at the moment addLine ran; totals, invoices and refunds use the line's value.

The product's price history is a separate concern — a product_price table with validity ranges if the business needs "what was the price on that day" for analytics.

A test that changes the product price after the order is placed and asserts the order total is unchanged encodes the rule.

The failure mode to guard against is a developer "fixing" a display by joining to product.price in a report query; a code review rule that order queries never join to product price columns is cheap.

Drill · Embeddables, inheritance, enums & types

This group tests whether you choose a mapping by the queries and constraints it produces, not by how it looks in Java.

Q55. "Compare SINGLE_TABLE, JOINED and TABLE_PER_CLASS for a Payment hierarchy with Card, Wallet and BankTransfer subclasses. Which would you pick and why?"

Reveal answer

Strong answer SINGLE_TABLE: one payment table with a dtype discriminator and the union of every subclass's columns.

Polymorphic queries are one scan with no joins; loading by id is one row; but card_last_four must be nullable because wallet rows have none, so the database cannot enforce subclass invariants, and a wide sparse table wastes space.

JOINED: a payment table with the shared columns plus card_payment, wallet_payment and bank_transfer tables joined on the primary key.

Every column is properly constrained and NOT NULL where it should be; loading a polymorphic list costs a left outer join per subclass, and inserting one payment is two INSERTs.

TABLE_PER_CLASS: three complete tables, no shared table; polymorphic queries become a UNION ALL across them, and IDENTITY ids are impossible because ids must be unique across tables.

For payments I would pick JOINED: the subclass-specific data is regulated (card data, bank details) and must be constrained, the hierarchy is small and stable so the joins are cheap, and most queries are by id or by order rather than polymorphic scans.

SINGLE_TABLE wins when subclasses differ by a column or two and reads are polymorphic and hot; TABLE_PER_CLASS almost never.

Land it Single table for speed and sparse columns, joined for constraints and normalisation — and say which of your queries are polymorphic before you choose.

Likely follow-ups
"With JOINED, what SQL does 'select p from Payment p where p.order.id = :id' produce, and how do you make it cheap?"

A SELECT from payment with a LEFT OUTER JOIN to each of the three subclass tables on the primary key, plus a CASE expression over which join matched to compute the discriminator — Hibernate 6 uses a synthetic clazz_ column derived from the joins.

For three subclasses that is three joins on primary-key indexes, which the planner handles in microseconds per row. It gets expensive with ten subclasses or with subclass tables that have wide rows.

Two ways to make it cheaper: add an explicit @DiscriminatorColumn to the JOINED hierarchy, which Hibernate honours to skip the CASE, and query the concrete subclass when you know it — select c from CardPayment c joins only two tables.

Polymorphic lists that are hot deserve a projection over the base table only.

"How does @Version work across a JOINED hierarchy — which table holds it?"

The root table, always.

The version, like the id, is declared on the base class and stored in payment; an update to a subclass-only column, say card_last_four, produces an UPDATE on card_payment for the data and an UPDATE on payment for the version bump with the version check in its WHERE clause.

So optimistic locking covers the whole object across both tables, and the base-table row lock is what serialises concurrent writers. Inserting a payment is an INSERT into payment then into the subclass table, in that order, and deleting is the reverse.

Declaring @Version on a subclass is a mapping error Hibernate rejects at startup.

"The team wants SINGLE_TABLE for speed but the regulator wants NOT NULL on card fields. Can you have both?"

Partly. In a single table, card_last_four must be nullable because wallet rows have no value, so a plain NOT NULL is impossible.

A CHECK constraint can express the subclass rule instead: check (dtype <> 'CARD' or card_last_four is not null), and Hibernate 6.2+ can generate discriminator-based checks for you when the columns are declared nullable = false on the subclass.

That satisfies the invariant at the database level without joins.

What it does not give you is column-level access control: with JOINED, card data lives in its own table that can have its own grants and its own encryption policy, which is often what "regulated" actually means. I would ask the regulator which they need before choosing.

"How would you change strategy on a live table with millions of rows?"

Expand and contract.

Going from SINGLE_TABLE to JOINED: create the subclass tables, backfill them from the wide table in batches keyed by id, deploy a version whose mapping reads JOINED but whose old columns are still present and ignored, verify counts match, then drop the old columns in a later release.

Going the other way: add the subclass columns to the base table nullable, backfill by joining, switch the mapping, drop the subclass tables later.

During the backfill window the application must write both shapes, which is a trigger or a dual-write in the service, so I would schedule it during a low-traffic period and keep the window short.

A schema migration that alters the mapping and the tables in one deploy has no rollback, which is why I never do it that way.

Q56 · Scenario. "A team stored an enum with @Enumerated(ORDINAL). Six months later they inserted a new constant alphabetically in the middle. What happened to production data, and how do you recover?"

Reveal answer

Strong answer Symptom: after the deploy, every row whose stored ordinal was at or above the insertion point now maps to the wrong constant — a SHIPPED order reads as REFUNDED, silently, with no exception.

Evidence: compare the enum declaration order before and after the change against a sample of rows whose true status is known from other columns or the audit log; the shift will be exactly one position from the insertion point.

Cause: ORDINAL stores the constant's index, so the mapping from integer to meaning is defined by source-code order, and the change rewrote that mapping for existing data.

Recovery: roll back the deploy immediately so the old order is restored and reads are correct again; then, in a migration with the table locked or in batches, rewrite the integers to a new scheme — either UPDATE ... SET status = status + 1 WHERE status >= N before deploying the reordered enum, or, better, migrate the column to text and switch to @Enumerated(STRING) so this can never recur.

Rows written between the bad deploy and the rollback need the audit log to disambiguate. Prevention: STRING always, a CHECK constraint listing the allowed names, and an ArchUnit test forbidding ORDINAL.

why @Enumerated(ORDINAL) broke six months laterruns offline
// BROKEN — ORDINAL stores the enum's POSITION as an integer.
@Enumerated(EnumType.ORDINAL)
private Status status;

enum Status { NEW, PAID, SHIPPED }
//              0    1      2         <- what is in the database

// Six months later someone adds a constant in alphabetical order:
enum Status { CANCELLED, NEW, PAID, SHIPPED }
//                0       1     2      3

// Every existing row now means something different:
//   a row storing 0 was NEW      -> reads back as CANCELLED
//   a row storing 1 was PAID     -> reads back as NEW
// No error. No exception. Silent, total data corruption across every row.

// FIX — STRING. Store the name, which is stable under reordering.
@Enumerated(EnumType.STRING)
private Status status;         // 'NEW', 'PAID', 'SHIPPED'

// The remaining risk with STRING is RENAMING a constant, which is at least a
// loud failure (IllegalArgumentException: No enum constant) rather than a
// silent misreading -- and it is fixable with a data migration.

// FOR A LONG-LIVED SCHEMA, the most robust option is an explicit stored code,
// decoupled from the Java name entirely:
@Converter(autoApply = true)
public class StatusConverter implements AttributeConverter<Status, String> {
    public String convertToDatabaseColumn(Status s) { return s.getCode(); }   // "N","P"
    public Status convertToEntityAttribute(String c) { return Status.fromCode(c); }
}

The failure mode is what makes ORDINAL unacceptable rather than merely inadvisable. Reordering an enum is a routine, innocuous-looking refactor that no test catches, and the result is every historical row silently changing meaning.

Land it ORDINAL couples your data to source-code order — the recovery is a migration, the prevention is one annotation parameter.

Likely follow-ups
"They rolled back, but the migration to STRING will take a week. How do you add the new constant safely in the meantime?"

Append it at the end of the enum, never in the middle. ORDINAL only breaks when existing positions shift; a constant added as the last value gets the next integer and every stored row keeps its meaning.

I would add a unit test that pins the ordinal of every existing constant — assertEquals(3, Status.SHIPPED.ordinal()) — so any reordering fails the build, and a comment on the enum saying why the order matters.

Removing a constant is equally dangerous and must be replaced by deprecating it in place. That buys the week; the migration to STRING with a CHECK constraint then removes the fragility for good, and the ordinal test is deleted with it.

"How do you migrate the column from ordinal integers to strings with no downtime?"

Expand and contract again. Add a nullable status_name varchar(32) column; deploy code that writes both columns — the entity keeps the @Enumerated(ORDINAL) field and gains a second mapped field, set in the same domain method — and still reads the integer.

Backfill in batches with update orders set status_name = case status when 0 then 'NEW' ... end where id between ? and ?. Deploy code that reads from the string and still writes both. Verify with a query that no row disagrees.

Then deploy code that maps only the string, and drop the integer column a release later. Add the CHECK constraint status_name in (...) as NOT VALID first and validate it separately so it takes no long lock. Four deploys, zero downtime, and every step reversible.

"What does Hibernate 6 and 7 do for enums by default — did anything change?"

As of Aug 2026: the JPA default is still ORDINAL, but Hibernate 6.2 and later generate a CHECK constraint listing the allowed values for both strategies when it creates the schema, and on MySQL and MariaDB it maps STRING enums to a native ENUM(...) column type; on PostgreSQL you can opt into a named enum type with @JdbcTypeCode(SqlTypes.NAMED_ENUM). That is why an upgrade with ddl-auto=validate can complain about an existing varchar column on MySQL. The generated CHECK constraint also means that appending a new constant requires a migration to alter the constraint, otherwise inserts with the new value fail — which is a better failure than silent misreads, but it surprises teams that expected enum changes to be code-only.

"How do you find which rows were written during the bad window, and fix them?"

The bad rows are the ones whose updated_at or Envers revision timestamp falls between the deploy and the rollback and whose status was written by the new code.

Those were written with the new ordinal mapping, so after the rollback they read wrong in the opposite direction.

The fix is update orders set status = status - 1 where status > :insertionPoint and updated_at between :deploy and :rollback, applied after checking a sample by hand against the audit log or order events.

Rows read but not written in that window were never changed on disk and need nothing.

If there is no reliable timestamp, the Envers _AUD table with the revision's timestamp is the second source, and the third is the application log of status transitions, which is why logging transitions with ids is worth its cost.

Q57. "How do you map a JSON column in Hibernate 6 and 7, and when is that better than a normalised table?"

Reveal answer

Strong answer Since Hibernate 6, @JdbcTypeCode(SqlTypes.JSON) on a field of any type serialisable by Jackson — a record, a Map<String, Object>, a list — maps it to jsonb on PostgreSQL and JSON on MySQL, with Hibernate handling the serialisation; no third-party type library is needed any more.

The field is compared by value for dirty checking, so a changed key inside the JSON produces an UPDATE of the whole column.

Hibernate 7 adds most of the SQL-standard JSON functions to HQL — json_value, json_query, json_exists — so you can filter on a key without dropping to native SQL. It is better than a normalised table when the data is genuinely schemaless or varies per row (product attributes that differ by category, integration payloads), when it is always read and written with its parent, and when you do not need to join on or constrain individual keys.

It is worse when keys are queried across rows at scale (an expression index on attributes->>'color' helps, but a real column is faster and constrainable), when individual keys are updated concurrently (the whole document is the lock and dirty-check unit), or when the document grows large and every parent load drags it along — split it into a lazy @OneToOne or a separate entity at that point.

Land it JSON for per-row shape variation that travels with its parent; columns for anything you filter, join or constrain across rows.

Likely follow-ups
"How do you query a JSON key from Spring Data without native SQL, concretely?"

In Hibernate 7, HQL: @Query("select p from Product p where json_value(p.attributes, '$.color') = :color"), and for existence json_exists(p.attributes, '$.ram_gb'); Hibernate translates them to the dialect's operators, attributes ->> 'color' on PostgreSQL and JSON_VALUE on MySQL. In Hibernate 6.6 those functions are not in HQL, so the options are a native query, or registering a custom function with a FunctionContributor that emits the arrow operator, or the sql() HQL function which embeds a SQL fragment: where sql('? ->> ?', p.attributes, 'color') = :color.

For a mapped record rather than a map, dirty checking compares the whole value; there is no per-key tracking. As of Aug 2026 I would write these against Hibernate 7 functions and keep a native fallback documented.

"What happens to dirty checking with a Map mapped as JSON?"

Hibernate deep-copies the map into the snapshot at load time and compares by value at flush, so attributes.put("color", "red") is detected and produces an UPDATE of the whole column. That works, with two costs.

The comparison serialises or walks the whole structure on every flush, which matters for large documents in large contexts.

And the type is Map<String, Object>, so a value read back from PostgreSQL jsonb comes out as whatever Jackson chose — an Integer for a small number, a Long for a large one, a Double for a decimal — and code that casts will break.

Mapping to a record with typed fields avoids that and gives the compiler a say, which is why I prefer a record per category over a map, with the map only for genuinely unknown keys.

"How would you index a JSON key, and how do you know the index is used?"

Two index kinds on PostgreSQL. A GIN index on the column, create index on product using gin (attributes jsonb_path_ops), serves containment queries such as attributes @> '{"color": "red"}', which is what a faceted filter compiles to.

A B-tree expression index, create index on product ((attributes ->> 'ram_gb')), serves equality and range queries on one key, and is the right choice for the two or three keys that dominate.

The planner only uses an expression index when the query's expression matches textually, so the HQL or native query must produce exactly attributes ->> 'ram_gb', and json_value in Hibernate 7 renders to a form that does — I verify with EXPLAIN (ANALYZE, BUFFERS) on the real generated SQL from the log.

MySQL 8 supports functional indexes and multi-valued indexes over JSON arrays for the same purpose.

"What are the concurrency implications of putting mutable data in JSON?"

The document is the lock unit.

Two transactions editing different keys of the same document both read the full JSON, modify their key, and write the full JSON back; without @Version the second write erases the first's key change, and with @Version the second fails and retries.

So JSON columns turn field-level concurrency into row-level concurrency, which is fine for data that is updated by one writer or rarely, and wrong for a settings blob many users edit at once.

The escape hatches are a partial-update statement in native SQL — PostgreSQL's jsonb_set or MySQL's JSON_SET — which updates one key atomically at the cost of bypassing the entity, or splitting the hot keys into columns. The Q73 design applies the same reasoning to entities.

Q58. "What is the difference between @MappedSuperclass and an @Entity base class with @Inheritance, and which do you use for audit fields?"

Reveal answer

Strong answer A @MappedSuperclass is a Java-level convenience: its fields are copied into each subclass's table as if declared there, but it is not an entity — it has no table, cannot be queried polymorphically (select a from AuditedEntity a fails), cannot be the target of a relationship, and has no identity of its own.

An @Entity base with @Inheritance is a real entity with a table (or a discriminator) and participates in polymorphic queries and relationships, at the cost of the join or discriminator machinery from Q55.

For audit fields — createdAt, createdBy, updatedAt, updatedBy, and often the id and version — @MappedSuperclass is right: you never want to query "everything that was created yesterday" across all entity types through the ORM, you do not want every table joined to a common base, and the fields are duplicated per table which is exactly the physical layout you want.

Combine it with @EntityListeners(AuditingEntityListener.class) and Spring Data's @CreatedDate and friends, and the base class becomes the single place auditing is wired.

Land it MappedSuperclass shares columns without sharing identity — the right tool for audit fields, the wrong one for anything you query as a family.

Likely follow-ups
"Can a @MappedSuperclass declare the @Id and @Version, and what does that constrain?"

Yes, and it is the usual pattern: abstract class BaseEntity { @Id @GeneratedValue Long id; @Version Integer version; ... }.

It constrains every subclass to the same id type and generation strategy, which is a feature for consistency and a nuisance for the one table that needs a UUID or an assigned key — that one simply does not extend the base.

The generator must be named per entity to get per-table sequences: with an unnamed @GeneratedValue Hibernate 6 derives the sequence name from each subclass's table, so the shared declaration still produces orders_SEQ and customer_SEQ.

Callbacks declared on the base, such as a @PrePersist that sets createdAt, run for every subclass, and @EntityListeners on the base is inherited unless a subclass says @ExcludeSuperclassListeners.

"What is the JPQL consequence — can you write 'select e from BaseEntity e'?"

No. A mapped superclass is not an entity, so it has no name in the JPQL namespace, and Hibernate rejects the query with "could not resolve entity".

Hibernate does support polymorphic queries over interfaces and non-entity superclasses in one specific way: select e from java.lang.Object e or a query naming a non-mapped superclass expands to a UNION-like set of queries over every entity that extends it, which is a Hibernate extension rather than JPA and is rarely what people want.

If a genuine "everything created yesterday" query is a requirement, that is the signal the base should be an @Entity with @Inheritance(strategy = JOINED), and you pay the join for it. For audit fields it is never a real requirement.

"How does Spring Data's auditing get wired through the base class in practice?"

The base class carries @EntityListeners(AuditingEntityListener.class) and the four fields annotated @CreatedDate, @LastModifiedDate, @CreatedBy and @LastModifiedBy, and the application has @EnableJpaAuditing with an AuditorAware bean. Hibernate instantiates the listener through Spring's SpringBeanContainer, so the listener can look up the auditor.

The dates come from a DateTimeProvider, so I set @EnableJpaAuditing(dateTimeProviderRef = "fixedClock") in tests.

Two things to know: the listener fires on @PrePersist and @PreUpdate, so bulk JPQL updates do not touch updated_at; and @LastModifiedDate is set only when the dirty check finds the entity changed, so a no-op save does not bump it, which is correct.

"Would you put the soft-delete flag in the same base class?"

No. Soft delete changes query semantics — every load and query for that entity is filtered — and not every entity should have that; audit fields are passive and universal.

Putting @SoftDelete on a base class applied to everything would silently filter reference data and join tables, and Hibernate applies the annotation per entity anyway.

I would keep @SoftDelete on the specific aggregates that the business "deletes" but must retain — customers, products — and leave it off lines, events and reference data. If most entities need it, a second mapped superclass, SoftDeletableEntity extends AuditedEntity, keeps the decision explicit per class.

The general rule is that a mapped superclass should share only what is true for every subclass without exception.

Q59 · Scenario. "A customer's balance is mapped as double and the finance team reports totals off by fractions of a cent after a year. Explain and fix without downtime."

Reveal answer

Strong answer Symptom: accumulated rounding error in money. Evidence: totals drift by amounts like 0.0000001 that grow with the number of operations, and the column type is double precision (or the Java field is double against a NUMERIC column, which converts on every read).

Cause: a binary floating-point double cannot represent 0.10 exactly, and every addition rounds; a year of transactions compounds into visible cents.

Fix, expand-and-contract style: add a balance_exact NUMERIC(19,4) column (a nullable add is instant on PostgreSQL and MySQL 8), deploy code that maps both — writing the BigDecimal to the new column and the double to the old — then backfill in batches using the finance team's reconciled values where the double is off, switch reads to the new field, then drop the double column a release later.

On the Java side the field becomes BigDecimal with @Column(precision = 19, scale = 4), and every arithmetic call uses an explicit RoundingMode; a Money embeddable record keeps the currency beside it.

Prevention: an ArchUnit test that no @Entity field of type double or float is named like money, and a schema lint that money columns are NUMERIC.

double for money, and what to use insteadruns offline
// BROKEN
@Column private double balance;

System.out.println(0.1 + 0.2);          // 0.30000000000000004
System.out.println(1.03 - 0.42);        // 0.6100000000000001

// double is IEEE-754 BINARY floating point. Values like 0.1 have no exact
// binary representation, exactly as 1/3 has no exact decimal one. Every
// arithmetic operation compounds the error, so a million-row sum drifts.

// FIX — BigDecimal, mapped to an exact decimal column.
@Column(precision = 19, scale = 4)      // -> DECIMAL(19,4) / NUMERIC(19,4)
private BigDecimal balance;

// AND THE THREE RULES FOR USING IT CORRECTLY:
//
// 1. NEVER construct from a double -- you inherit the error you were avoiding.
new BigDecimal(0.1);              // 0.1000000000000000055511151231257827...
new BigDecimal("0.1");            // exactly 0.1        <- the String constructor
BigDecimal.valueOf(0.1);          // 0.1  (goes via Double.toString)
//
// 2. Division REQUIRES a rounding mode, or it throws ArithmeticException
//    on any non-terminating result.
total.divide(count, 2, RoundingMode.HALF_UP);
//
// 3. equals() COMPARES SCALE. 2.0 and 2.00 are not equal.
new BigDecimal("2.0").equals(new BigDecimal("2.00"));      // false
new BigDecimal("2.0").compareTo(new BigDecimal("2.00"));   // 0  <- use this

// The alternative used in high-volume systems: store minor units as a long
// (pence, cents) and format for display. Exact, fast, and no scale surprises.

Rule 3 causes test failures that look like framework bugs. Two amounts that are numerically identical are not equals if their scales differ, so an assertion comparing 2.0 with 2.00 fails for a reason that has nothing to do with the value.

Land it Money is BigDecimal in Java and NUMERIC in the database, and the switch is a four-step expand-and-contract, not a column type change.

Likely follow-ups
"The backfill from the double column is itself imprecise. How do you get exact values?"

You do not get them from the double; you get them from the ledger. A balance is a sum of transactions, so the exact value is sum(amount) over the account's transaction rows, provided those amounts were stored exactly.

If the transaction amounts were also doubles, the individual amounts are usually exact when rounded to the currency's minor unit — a single payment of 19.99 stored as a double reads back as 19.99 to two decimals — so the backfill recomputes each balance as the sum of the rounded amounts, and the finance team's reconciliation catches the handful where rounding is ambiguous.

Where there is no ledger, the best available value is round(balance::numeric, 2), and the finance team signs off on the difference, which is a business decision to record, not an engineering one.

"Why NUMERIC(19,4) rather than (19,2), and how does Hibernate handle the scale?"

Two extra decimal places let intermediate values — tax on a unit price, a pro-rata refund — be stored with more precision than the currency's minor unit, so rounding happens once at presentation rather than compounding through every step. Many financial systems use four; some use six. Hibernate maps BigDecimal with @Column(precision = 19, scale = 4) to numeric(19,4) in generated DDL and validates against it, but at runtime the driver sends whatever scale the Java value has and the database rounds to the column's scale on insert — silently on PostgreSQL. So the code must set the scale explicitly, amount.setScale(4, RoundingMode.HALF_EVEN), before it is stored, and the dirty check compares BigDecimal by compareTo so 1.5 and 1.50 are not seen as a change.

"How do you represent money in the domain so this cannot recur?"

A Money value type: an @Embeddable record with a BigDecimal amount and a Currency currency, arithmetic methods that refuse to add different currencies and that round with an explicit mode, and no public constructor taking a double.

Every entity that holds money holds a Money, with @AttributeOverride when there are two. The alternative is the JSR-354 javax.money API with Moneta and a Hibernate UserType, which some teams use; the record is lighter and enough.

The enforcement is an ArchUnit rule that no @Entity field is of type double, float, Double or Float unless annotated with a team-specific @NotMoney, and a Flyway check that no column named like money is a floating type.

"What about the dual-write period — how do you make sure both columns stay consistent?"

The entity has both fields and one domain method sets both from the same BigDecimal: the exact column gets the value, the legacy column gets value.doubleValue(). No code path sets one without the other, which a unit test on the domain method enforces.

A nightly query counts rows where abs(balance_exact - balance::numeric) > 0.005 and alerts; expected to be zero for rows written after the deploy and some for older rows until the backfill finishes.

Reads switch to the exact column only when that count is zero for rows updated since the deploy. Then writes to the legacy column stop, and it is dropped a release later.

The whole window is typically two weeks, and the query is the evidence at each gate.

Q60. "How does Hibernate handle Instant, LocalDateTime and OffsetDateTime, and which should a global service store?"

Reveal answer

Strong answer LocalDateTime has no zone; Hibernate maps it to TIMESTAMP without time zone and stores the literal wall-clock digits — which means the value's meaning depends on whatever zone the writer assumed, and a JVM in a different zone reads a different instant.

Instant is an absolute point on the timeline; Hibernate 6.2 and later map it to TIMESTAMP WITH TIME ZONE, and the JDBC driver converts to and from UTC so the stored value is unambiguous.

OffsetDateTime carries an offset; by default Hibernate normalises it to UTC on write and the offset is lost on read (you get the value in UTC), unless hibernate.timezone.default_storage: COLUMN stores the offset in a separate column. ZonedDateTime loses its region id entirely, keeping only the offset.

A global service should store Instant in a timestamptz column, convert to the user's zone at the presentation layer, and keep the JVM and the database session in UTC (hibernate.jdbc.time_zone: UTC) so no driver conversion can surprise you.

Store a LocalDate only for calendar facts like a birth date, which genuinely have no instant. The Hibernate 7 validation change in Q38 is this rule enforced at startup.

Land it Instant in timestamptz, everything in UTC end to end, and LocalDateTime only when the wall clock is the actual fact.

Likely follow-ups
"What does hibernate.jdbc.time_zone actually do, and does it replace setting the JVM to UTC?"

It makes Hibernate pass a UTC Calendar to setTimestamp and getTimestamp, so the driver converts using that zone rather than the JVM default.

It protects the timestamp-without-time-zone path, where the driver would otherwise use the JVM zone and a pod running in a non-UTC zone would write shifted values.

It does not change what the database session's TimeZone is, which matters for timestamptz on PostgreSQL — the driver handles that conversion itself — and it does not affect now() in native SQL.

So I set all three: the JVM with -Duser.timezone=UTC, hibernate.jdbc.time_zone=UTC, and the database's default time zone to UTC, and then the conversions are all identities and nothing can drift.

"How do you store an appointment at 9am local time that must stay 9am if the zone's rules change?"

Store the local date-time and the zone id, not an instant. A LocalDateTime in a plain timestamp column and a String or ZoneId column holding "Europe/London", converted to an instant at read time with the current tz database rules.

If you store the instant, a government changing daylight-saving rules between booking and appointment shifts the appointment by an hour. ZonedDateTime in Hibernate keeps only the offset by default, which is not enough; @TimeZoneStorage(COLUMN) stores the offset, still not the zone id.

So this is the one case where LocalDateTime plus an explicit zone column is correct, and it should be documented on the entity because it looks like the anti-pattern from the answer.

"How would you find timestamps that were written in the wrong zone historically?"

Look for the fingerprint of the JVM zone.

If pods ran in Europe/Berlin writing to a plain timestamp column, the stored values are one or two hours ahead of UTC depending on the season, and rows cluster at an hour offset compared with a trustworthy source such as a message broker timestamp, an Envers revision written by a different path, or the row's xmin commit time recovered from pg_xact_commit_timestamp if track_commit_timestamp was on.

The correction is update ... set created_at = created_at at time zone 'Europe/Berlin' at time zone 'UTC' for the affected range, after the column is timestamptz.

If the offset varied by pod, it is unfixable in general, which is the argument for standardising on UTC before the first row.

"Which type should the @Version timestamp or the audit fields use?"

Instant, stored in timestamptz, for anything that records when something happened — created_at, updated_at, published_at. Spring Data's @CreatedDate supports Instant directly.

For the version column, an integer as in Q70; if a timestamp version is imposed, still Instant, so that two pods in different zones cannot produce a version that looks older.

The only temporal fields that should be local types are calendar facts: a birth date as LocalDate, a store's opening hour as LocalTime, an appointment as above.

A quick review heuristic: if the field name ends in _at, it is an Instant; if it ends in _date or _day, it might be a LocalDate.

Q61 · Design. "Design the mapping for a product catalogue where products have category-specific attributes (a laptop has RAM, a shirt has size) and the catalogue is searched by those attributes."

Reveal answer

Strong answer Requirements: attribute sets differ by category and change often (new categories monthly), search filters on attributes must be fast, and the core product fields — SKU, name, price, category — are queried constantly and must be constrained.

Design: a product table with the stable columns as real, constrained columns; a jsonb attributes column mapped with @JdbcTypeCode(SqlTypes.JSON) to a Map<String, Object> for the category-specific data; a category_attribute_schema table (or JSON Schema per category) that the application validates against on write, so the JSON is not a free-for-all; and a GIN index on the attributes column for containment queries (attributes @> '{"ram_gb": 16}'), with expression B-tree indexes on the two or three attributes that dominate filtering and range queries.

Searches run as native queries or HQL with Hibernate 7's json_value, returning projections.

Trade-offs: JSON attributes are not constrained by the database, so validation lives in code; a GIN index is larger and slower to update than a B-tree, which is fine for a catalogue that is read a thousand times more than it is written.

Alternatives rejected: the entity-attribute-value pattern (one row per attribute), which turns every product load into a pivot and every filter into a self-join per attribute; and JOINED inheritance with one subclass per category, which needs a schema migration and a Java class for every new category.

For full-text and faceted search at scale, mirror the catalogue to a search index and keep PostgreSQL as the source of truth.

Land it Columns for what is stable and constrained, JSON with a GIN index for what varies by category, and a search index when facets outgrow the database.

Likely follow-ups
"Requirement change: attributes must be validated by the database, not just the application. Does JSON survive?"

Partly. PostgreSQL can enforce structure on jsonb with CHECK constraints — check (jsonb_typeof(attributes -> 'ram_gb') = 'number') — and, with the pg_jsonschema extension, a full JSON Schema check per row, keyed by category through a trigger that looks up the schema.

That covers types and required keys.

What it cannot do is foreign keys from inside the document — "size must be one of the sizes in the size table" — so any attribute that references other data should be promoted to a column or a child row.

So the design becomes: stable columns for constrained references, JSON with a schema check for typed leaf values, and the category's schema stored in a table so the trigger and the application validate against the same source.

If the regulator wants everything relational, the EAV alternative or a table per category is the price, and I would push back with the query-cost numbers.

"What would you cut under time pressure?"

The schema table and the GIN index.

Ship the product table with a jsonb attributes column mapped to Map<String, Object>, validate in the application against a per-category record type, and add a B-tree expression index only on the one or two attributes the first search screens use.

Searches that are not indexed are sequential scans over a catalogue that fits in memory, which is fine at launch scale.

What I would not cut is keeping SKU, name, price and category as real columns, because moving them out of JSON later means touching every query, and I would not cut the application-side validation, because an unvalidated JSON column becomes unqueryable garbage within a month. The search index mirror is a phase-two item by design.

"Why is EAV so bad — give the SQL for 'laptops with 16 GB RAM and a 15-inch screen'."

With an attribute(product_id, name, value) table, that filter needs one join per predicate: select p.* from product p join attribute a1 on a1.product_id = p.id and a1.name = 'ram_gb' and a1.value = '16' join attribute a2 on a2.product_id = p.id and a2.name = 'screen_in' and a2.value = '15'.

Three predicates, three self-joins; each adds a hash or nested-loop join over a table with ten rows per product. Loading a product's attributes is a pivot — a query returning N rows per product that the application folds into a map.

Values are strings, so numeric range filters need casts that defeat indexes, and there is no per-attribute type. JSON with a GIN index answers the same filter as attributes @> '{"ram_gb":16,"screen_in":15}' in one index probe. EAV made sense before databases had JSON; it does not now.

"When does the search-index mirror become mandatory, and how do you keep it consistent?"

When the queries need relevance ranking, fuzzy matching, or facet counts across millions of products in under 100 milliseconds — PostgreSQL full-text search and GIN indexes cover a lot, but facet counts across many attributes are aggregations the database recomputes per query.

The mirror is OpenSearch or a similar engine fed from the outbox: every product change writes an outbox row in the same transaction, a relay updates the index, and the index is eventually consistent by a second or two.

Consistency is verified by a periodic reconciliation comparing product updated_at against the index document's version, and the search results are hydrated from PostgreSQL by id so that stale documents can only affect ranking and never show wrong prices.

The database stays the source of truth, which is the line I would hold.

Q62. "What is @DynamicInsert, what is @Generated / @ColumnDefault, and how do they interact with database-side defaults?"

Reveal answer

Strong answer By default Hibernate's INSERT names every mapped column and writes NULL for a field you did not set — so a database default like created_at DEFAULT now() never fires, because Hibernate explicitly sent null.

@DynamicInsert on the entity omits null-valued columns from the INSERT, so database defaults apply; the cost is a different SQL text per null pattern, which weakens statement caching and batching, as with @DynamicUpdate in Q11.

@ColumnDefault("now()") only affects generated DDL — it puts the default in the CREATE TABLE — and does nothing at runtime.

@Generated (Hibernate 6.5 and later; earlier @Generated(GenerationTime.INSERT)) tells Hibernate the database computes the column, so Hibernate excludes it from INSERT and, after the flush, re-reads it — on PostgreSQL through INSERT ... RETURNING in one round trip, elsewhere with a follow-up SELECT — so the entity holds the database's value.

The clean pattern for "created_at set by the database" is @Generated @Column(insertable = false, updatable = false) on the field with the default declared in the migration; the clean pattern for "created_at set by the application" is simply initialising the field in Java, which is what the primer's entities do because it keeps the value visible before flush and needs no re-read.

Land it Hibernate writes what it maps, including nulls — either let Java set the value or tell Hibernate the column is @Generated and let the database own it.

Likely follow-ups
"Show me how the @Generated re-read works on MySQL versus PostgreSQL, and what it costs."

On PostgreSQL, Hibernate 6 and 7 append RETURNING created_at to the INSERT, so the generated value arrives in the same round trip as the insert; for UPDATE-time generated columns it uses UPDATE ... RETURNING the same way.

On MySQL there is no RETURNING for arbitrary columns, so Hibernate issues a select created_at from orders where id = ? immediately after the INSERT, a second round trip per row, and that SELECT cannot be batched.

So on MySQL a table with a database-generated timestamp doubles the insert cost. The setting hibernate.jdbc.use_get_generated_keys covers only identity keys, not other columns.

That asymmetry is one reason I default to setting timestamps in Java, and reserve @Generated for values only the database can compute, such as a trigger-maintained sequence number.

"What is the difference between @Generated and @Column(insertable = false, updatable = false)?"

insertable = false, updatable = false only removes the column from Hibernate's INSERT and UPDATE; Hibernate never reads it back after a write, so the entity's field stays null until the next load.

@Generated does the exclusion and adds the re-read, so the field is populated after flush.

You need @Generated when the code uses the value in the same transaction — returning createdAt in the response of a create call, or a database-computed order_number that goes into an event.

You can use the plain column flags when the value is only read in later transactions, or for a column another system maintains. Hibernate 6.5 changed @Generated to take an event array of EventType.INSERT and UPDATE, replacing the old GenerationTime enum.

"When would you use @DynamicInsert despite the batching cost?"

On a legacy table with dozens of columns that have database defaults you cannot move into Java, where the alternative is mapping every default in the entity and keeping them in sync with the DDL. Or on a very wide table where most inserts set a handful of columns and the full INSERT text is kilobytes.

In both cases the batching loss matters only if the table is bulk-inserted, which wide legacy tables rarely are.

I would measure first: with batch_size=50 and identical null patterns, dynamic inserts still batch, because the SQL text is the same across the batch; only varying patterns break it. The test is the org.hibernate.engine.jdbc.batch log showing batch sizes of one where fifty was expected.

"What about columns that must be set on update by the database, like updated_at via a trigger — how does Hibernate cooperate?"

Map the field with @Generated(event = EventType.UPDATE) — or @Generated(event = {INSERT, UPDATE}) if the trigger sets it on both — and @Column(insertable = false, updatable = false) so Hibernate never writes it and re-reads it after each write.

If a trigger maintains it and the application also has Spring Data's @LastModifiedDate on the same column, the two fight: Hibernate writes its value, the trigger overwrites it, and the entity holds the wrong one until reload. Pick one owner.

My preference is the application, because tests can control the clock and the value is visible before flush; the trigger wins only when other writers bypass the application, which is the same argument as Q29's audit triggers.

Drill · Optimistic & pessimistic locking

This group tests whether you can choose a locking strategy from the conflict rate, and handle the failure each one produces.

Q63. "Walk through exactly what SQL @Version produces, where the exception is raised, and what a correct retry looks like."

Reveal answer

Strong answer On load, the version column comes back with the entity and is stored in the snapshot. On flush, a dirty entity's UPDATE becomes update orders set status=?, ..., version=? where id=? and version=?, binding the incremented version in the SET and the loaded version in the WHERE. Hibernate checks the JDBC update count: one row means success; zero rows means someone else changed the version, and Hibernate throws StaleObjectStateException, wrapped as OptimisticLockException by JPA and as ObjectOptimisticLockingFailureException by Spring.

The exception surfaces at flush time — usually at the commit inside the @Transactional proxy, which is after your method returned — so a try/catch inside the service method does not see it.

A correct retry therefore lives outside the transaction boundary: a caller method (or Spring Retry's @Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3) on a non-transactional wrapper) that invokes the transactional method again, so that the retry reloads the entity fresh, reapplies the business change to current data, and attempts a new commit.

Retrying by calling save() again on the same stale object cannot work, because its version is still the old one. Deletes are versioned too: delete ... where id=? and version=?.

the SQL @Version produces, and where the exception surfacesruns offline
@Entity
public class Product {
    @Id private Long id;
    @Version private int version;      // Hibernate owns this; never set it yourself
    private int stock;
}

@Transactional
public void decrement(Long id) {
    Product p = repo.findById(id).orElseThrow();   // select ... version = 3
    p.setStock(p.getStock() - 1);
}   // AT FLUSH:
    //   update product set stock = ?, version = 4 where id = ? and version = 3
    //                                                          ^^^^^^^^^^^^^^
    // If another transaction already committed, that row has version 4,
    // 0 rows are updated, and Hibernate throws.

// WHERE THE EXCEPTION IS RAISED — and this is the part that matters:
// NOT at the setter. At FLUSH, which is usually at COMMIT, i.e. AFTER your
// method has returned. So a try/catch inside the method catches nothing;
// the caller sees ObjectOptimisticLockingFailureException from the proxy.

// WHICH IS WHY THE RETRY MUST BE OUTSIDE THE TRANSACTION:
@Service
public class StockFacade {
    @Retryable(retryFor = ObjectOptimisticLockingFailureException.class,
               maxAttempts = 3, backoff = @Backoff(delay = 50, multiplier = 2))
    public void decrement(Long id) {
        inner.decrementInTx(id);      // a NEW transaction, and a FRESH read, per attempt
    }
}
// Retrying inside the same transaction re-uses the stale entity and a
// transaction already marked rollback-only: it fails identically three times.

The flush-time timing explains the whole retry design. Because the conflict is detected at commit rather than at the write, the only correct retry boundary is outside the transaction — which is why the retry and the transactional work must live in different beans.

Land it The check is a WHERE clause on the version, the failure is a zero update count at flush, and the retry must re-enter the transaction from outside.

Likely follow-ups
"Show me the retry wrapper concretely, and explain why @Retryable on the transactional method itself does not work."

A separate bean: @Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3, backoff = @Backoff(delay = 50, multiplier = 2)) public void markPaid(long orderId) { orderService.markPaid(orderId); }, with OrderService.markPaid carrying the @Transactional.

The retry proxy wraps the outer call, so each attempt enters the transactional proxy afresh, opens a new context, reloads the order with the current version, and reapplies the change.

Putting both annotations on one method fails because Spring orders the retry interceptor inside or outside the transaction interceptor depending on @Order; by default the retry can run inside the transaction, retrying on a context that is already marked rollback-only and holding stale objects, so every attempt fails.

As of Aug 2026 Spring Framework 7 has its own @Retryable in core, with the same ordering caveat.

"What if the conflicting change was semantically compatible — both users added a different tag?"

Then the retry makes it work: the second attempt reloads the order, sees the first user's tag already present, adds its own, and commits with the new version.

Optimistic locking plus reload-and-reapply is an automatic merge for commutative operations, as long as the operation is expressed as an intent — "add tag X" — rather than a state — "the tags are now [X, Y]".

That is the argument for domain methods over merges from Q26: a merged detached object cannot be reapplied because it carries a snapshot, whereas order.addTag("X") can.

Where the operations are not commutative — two users setting different titles — the retry would silently overwrite, and the correct behaviour is to surface the conflict to the user with both values, which is the Q73 design.

"How do you turn the exception into a proper HTTP response?"

In a @ControllerAdvice, map ObjectOptimisticLockingFailureException — Spring's translation of Hibernate's StaleObjectStateException — to 409 Conflict with a problem-details body that names the resource and, if the service can afford a read, the current version so the client can refetch and retry.

If the client sent an If-Match header and the service compared versions before applying, the earlier failure is a 412 Precondition Failed, which is the more precise status.

I count both by endpoint in Micrometer, because a rising conflict rate on one endpoint is the Q64 signal. What I do not do is retry automatically in the controller for non-idempotent operations, because the user's intent may have changed once they see the other edit.

"Does the version check also protect deletes and what happens when the row is already gone?"

Yes: delete from orders where id = ? and version = ?. If another transaction updated the row, the version differs, zero rows match, and Hibernate throws the same stale-state exception.

If another transaction deleted the row, zero rows match for the same reason, and again it is reported as an optimistic lock failure rather than "not found" — Hibernate cannot tell the two apart from an update count.

The handler should therefore treat a stale-state exception on delete as "reload and decide": if the reload finds nothing, the delete already happened and the operation is idempotently complete; if it finds a newer version, show the conflict.

Spring Data's deleteById loads first, so it throws EmptyResultDataAccessException or, since Spring Data 3, silently does nothing when the row is absent, which changes the semantics again.

Q64 · Scenario. "An OptimisticLockException storm hits every month-end: thousands of failures on an account_summary row that a nightly job and hundreds of users both update. Diagnose and redesign."

Reveal answer

Strong answer Symptom: a burst of ObjectOptimisticLockingFailureException concentrated on a few rows at a predictable time. Evidence: group the failures by entity id — they cluster on hot summary rows; correlate timing with the month-end job; check the retry policy, because naive retries multiply the load.

Cause: optimistic locking assumes conflicts are rare, and here they are the normal case — a single hot row updated by many writers, each doing load-compute-save on the whole row, so every write invalidates every other in-flight write.

Redesign, ranked: one, stop updating a shared row from concurrent writers — make the summary an append-only ledger (account_entry rows) and compute the balance by sum or by a materialised summary updated by one writer; two, if the row must stay, replace load-modify-save with an atomic set-based statement, update account_summary set balance = balance + :delta where id = :id via @Modifying, which never conflicts because it does not carry a version check; three, for the nightly job specifically, take a PESSIMISTIC_WRITE lock and process each account in a short transaction so users queue for milliseconds instead of failing.

Fix the retry to exponential backoff with jitter and a cap. Prevention: a metric on optimistic-lock failures per entity type with an alert threshold, so contention is visible before month-end.

Land it Optimistic locking on a hot row is the wrong tool by definition — make the write additive or make it pessimistic and short.

Likely follow-ups
"They switched to the atomic 'balance = balance + delta' update and now the nightly job's totals are wrong. Why?"

Because the job still does load-compute-save on the summary row and overwrites the users' increments.

The atomic update has no version check, so it never conflicts, but it also never bumps the version; the job loaded the row at 22:00, computes a new balance from its own inputs, and writes the full row at 22:05 with where version = ? — which succeeds because nobody bumped the version — erasing five minutes of increments.

Once one writer is additive, every writer must be: the job must also express its change as a delta, or the job must lock the row with PESSIMISTIC_WRITE and recompute inside a transaction short enough that users wait milliseconds.

The lesson is that the write model of a hot row must be consistent across all writers, and the test is a concurrent job-plus-users simulation.

"What does the ledger design cost on the read side, and how do you bound it?"

A balance read becomes select sum(amount) from account_entry where account_id = ?, which for an account with a million entries is a scan of a million rows per read.

The bound is a periodic snapshot: a account_balance_snapshot row written by a single job — say nightly, or every N entries — holding the balance as of an entry id, and the read becomes snapshot plus the sum of entries after it, which is a few rows.

That is a materialised running total with one writer, so no contention. The trade-off is that the snapshot job is a piece of infrastructure to monitor.

For the month-end job specifically, it reads the ledger rather than updating a shared row, and its writes become entries too, which never conflict.

"Why is the naive retry making it worse — quantify it."

With N concurrent writers on one row and immediate retries, each commit invalidates every other in-flight attempt, so a successful commit costs on the order of N failed attempts, and the total work for N writers is proportional to N squared.

Two hundred concurrent users each retrying three times with no backoff is up to six hundred attempts, each a SELECT plus a failed UPDATE, converging on the same row's lock and the same buffer page.

Exponential backoff with jitter spreads the attempts so that fewer are in flight at once, which is what makes optimistic locking usable at moderate contention.

At month-end contention it is still the wrong tool, and the metric that says so is the ratio of failed to successful updates on that entity, which should be well under one percent normally.

"How would you verify the redesign under realistic load before month-end?"

A load test in staging that replays last month-end's write pattern — the job plus a few hundred simulated users — against the new schema, asserting three things: zero ObjectOptimisticLockingFailureException in the logs, p99 latency of the user write under 100 milliseconds, and the final balance equal to the sum of all applied deltas, which is the correctness check that catches lost updates.

I would also run the old code path in the same harness to confirm the harness reproduces the storm; a load test that cannot reproduce the problem cannot prove the fix.

Then, at the real month-end, a dashboard with the conflict counter and the lock-wait count from pg_stat_activity on that table, watched by a person.

Q65. "What are OPTIMISTIC_FORCE_INCREMENT and PESSIMISTIC_FORCE_INCREMENT for? Give a mapping where you need them."

Reveal answer

Strong answer Both bump a parent's version even though the parent's own columns did not change.

The case: an order's lines are separate rows, so two transactions can each add a line to the same order without either touching the orders row, and the order's @Version never detects the conflict — yet the business rule "an order total equals the sum of its lines" was broken by the two concurrent adds.

Locking the order with LockModeType.OPTIMISTIC_FORCE_INCREMENT (em.find(Order.class, id, OPTIMISTIC_FORCE_INCREMENT)) makes Hibernate issue update orders set version = version + 1 where id = ? and version = ? at commit, so the second transaction fails its version check and must retry: the root's version now guards the whole aggregate.

PESSIMISTIC_FORCE_INCREMENT does the same but takes the row lock immediately with SELECT ... FOR UPDATE and increments the version at that moment, so the second transaction waits instead of failing.

Plain LockModeType.OPTIMISTIC without increment only verifies at commit that the version is unchanged, without bumping it — useful for a reader that must fail if the row changed underneath it.

In the primer's model, the root recomputes total on every line change, which dirties the orders row and increments the version naturally; force-increment is for aggregates whose root has nothing to recompute.

Land it Force-increment turns the root's version into a lock over the whole aggregate, so child edits conflict where the business says they should.

Likely follow-ups
"What SQL does OPTIMISTIC_FORCE_INCREMENT actually run, and when?"

At flush, after the entity updates, Hibernate issues update orders set version = ? where id = ? and version = ? for the locked entity, binding the incremented version and the loaded one, even if no other column changed; a zero update count throws the stale-state exception.

If the order was also dirty, the increment is folded into the normal UPDATE and no separate statement appears.

Plain LockModeType.OPTIMISTIC instead issues select version from orders where id = ? at commit and compares it with the loaded version, throwing if it moved — a read verification without a write.

The verify-only mode is cheaper and useful for a reader that computes something from the order and must know it did not change; the force-increment mode is what protects writers of the children.

"How do you apply it through Spring Data rather than the EntityManager?"

Declare a repository method with the lock annotation: @Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT) Optional<Order> findWithLockById(Long id);. Spring Data passes the mode to the query, and the lock applies to the returned entity for the rest of the transaction.

Derived query names are fine, and it works with @Query JPQL as well.

Two caveats: the method must run inside the caller's transaction, otherwise the repository's own transaction ends immediately and the lock with it; and the lock applies to the root entity of the query, not to fetched children, so a join fetch does not lock the lines.

For pessimistic variants the same annotation takes PESSIMISTIC_WRITE and @QueryHints carries the timeout hint.

"Give a case where PESSIMISTIC_FORCE_INCREMENT is better than the optimistic variant."

A warehouse pick where several workers add lines to the same order in quick succession, and each add is a small, fast transaction. With the optimistic variant, workers collide constantly and the retries waste the round trips; with PESSIMISTIC_FORCE_INCREMENT, each transaction takes select ... for update on the order row at the start, bumps the version immediately, adds its line, and commits within milliseconds, so the next worker waits a few milliseconds rather than failing.

It is the Q64 reasoning applied to an aggregate root: when conflict is the normal case and the critical section is short, waiting beats retrying.

The cost is that the lock is held for the whole transaction, so it must contain nothing slow, and the timeout hint must be set so a stuck holder does not queue everyone.

"How would you verify that child edits actually conflict after adding it?"

The two-thread test from Q37, adapted: both transactions load the same order with the force-increment lock, both add a line, both commit; assert exactly one succeeds and the other throws ObjectOptimisticLockingFailureException, and that the surviving order has exactly one new line.

Then the negative control: the same test without the lock, asserting both commit and the order has two new lines and an unchanged version, which documents the gap the lock closes.

I would also assert on the SQL that the version-bump UPDATE appears in the successful transaction. That pair of tests is the executable definition of the aggregate's concurrency contract, and I would keep both in the suite.

Q66. "PESSIMISTIC_READ versus PESSIMISTIC_WRITE — what SQL does each produce on PostgreSQL and MySQL, and what does 'lock timeout' mean in each?"

Reveal answer

Strong answer PESSIMISTIC_WRITE becomes SELECT ... FOR UPDATE on both engines: an exclusive row lock that blocks other FOR UPDATE, FOR SHARE, UPDATE and DELETE on those rows until commit, while plain reads under MVCC continue unblocked. PESSIMISTIC_READ becomes SELECT ... FOR SHARE on PostgreSQL and SELECT ... FOR SHARE (older syntax LOCK IN SHARE MODE) on MySQL 8: a shared lock that lets other readers take the same shared lock but blocks writers — used to guarantee a row you are reading cannot change before you commit, without excluding other readers.

The jakarta.persistence.lock.timeout hint, in milliseconds, maps to engine features: PostgreSQL has no per-statement lock timeout in the SQL, so Hibernate maps 0 to NOWAIT (fail immediately) and otherwise sets lock_timeout on the session where the dialect supports it; MySQL 8 supports NOWAIT for zero and otherwise innodb_lock_wait_timeout applies, defaulting to 50 seconds.

Hibernate's -2 (SKIP LOCKED) makes both engines skip rows currently locked by others, which is the primitive behind a database-backed queue. A lock timeout produces LockTimeoutException, and a detected deadlock produces PessimisticLockException after the engine kills one transaction — both should be treated as retryable.

Going deeper Be precise about what the timeout hint does on PostgreSQL. Hibernate's PostgreSQL dialect renders jakarta.persistence.lock.timeout = 0 as FOR UPDATE NOWAIT and -2 as FOR UPDATE SKIP LOCKED; a positive millisecond value has no per-statement syntax in PostgreSQL, and as of Aug 2026 Hibernate does not translate it into a SET LOCAL lock_timeout, so a hint of 3000 on PostgreSQL waits indefinitely.

To get a bounded wait there, set lock_timeout yourself: globally through the pool's connection-init-sql: SET lock_timeout = '3s', or per transaction with a native SET LOCAL lock_timeout = '3s' at the start of the method.

MySQL 8 does support NOWAIT and SKIP LOCKED in the statement, and a positive value falls back to the session's innodb_lock_wait_timeout, which you can set per session with SET innodb_lock_wait_timeout = 3.

Hibernate 7 adds Timeouts.NO_WAIT, Timeouts.SKIP_LOCKED and a Timeout find option through Jakarta Persistence 3.2, which makes the intent readable, but the underlying database behaviour is unchanged.

The way to verify what actually happens is to hold a lock in one session and time the second session's failure: NOWAIT fails instantly, SKIP LOCKED returns without the row, and an unset timeout on PostgreSQL simply hangs.

Land it FOR UPDATE to exclude writers and other lockers, FOR SHARE to exclude only writers — and set a timeout, because the default on MySQL is fifty seconds of waiting.

Likely follow-ups
"Does FOR UPDATE lock the rows of a joined table too?"

On PostgreSQL, SELECT ... FOR UPDATE locks rows from every table in the FROM clause unless you name the tables with FOR UPDATE OF orders; Hibernate renders the OF clause for the entity you locked when the query has joins, so a join fetch of the customer does not lock the customer row.

On MySQL, InnoDB locks every row it scanned in all joined tables, and there is no OF clause until MySQL 8.0, which added it.

Locking scanned rows is also why a FOR UPDATE query without a usable index on MySQL can lock an entire table's rows — it scanned them all.

So on MySQL I make sure the locking query hits an index and locks by primary key, which the EXPLAIN plan confirms.

"What is the difference between a lock timeout and a deadlock, in the exception you catch and what you do next?"

A lock timeout means you waited the configured time and the holder had not released; the database returns an error, Hibernate throws LockTimeoutException, and Spring translates to CannotAcquireLockException.

Nothing is wrong with the data; the holder was just slow, so a retry after a short pause is right, and a persistent timeout points at a transaction that holds locks across slow work.

A deadlock means two transactions each wait for the other; the database detects it within a second and kills one, whose statement fails with a deadlock error — PessimisticLockException from Hibernate, DeadlockLoserDataAccessException from Spring.

The killed transaction is rolled back and must be retried from the start, and the deadlock report must be read, because it indicates inconsistent lock ordering that a retry does not fix.

"When would you use PESSIMISTIC_READ in a real service?"

When a transaction reads a parent row to make a decision and must ensure the parent does not change before it commits, but other readers should not be blocked.

Checking that an account is not frozen before inserting a withdrawal: FOR SHARE on the account row lets other withdrawals check concurrently while blocking the admin's UPDATE account SET frozen = true until they commit, so a freeze cannot slip in between the check and the insert.

With PESSIMISTIC_WRITE the withdrawals would serialise on the account row unnecessarily.

The subtlety on PostgreSQL is that FOR SHARE and foreign-key checks interact — inserting a child takes a FOR KEY SHARE on the parent automatically — so for the plain "parent must exist" case you get the protection for free without any explicit lock.

"How do you see who holds the lock in production?"

On PostgreSQL, pg_locks joined to pg_stat_activity, or the shortcut select pid, pg_blocking_pids(pid), query, state, xact_start from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0, which lists waiters and the pids blocking them; the blocker's query and xact_start tell you what it is doing and how long it has held the transaction.

On MySQL 8, performance_schema.data_lock_waits joined to data_locks and information_schema.innodb_trx gives the same picture. The common finding is a blocker in state idle in transaction — an application thread holding a lock while doing something outside the database, which is Q18 again.

Setting idle_in_transaction_session_timeout on PostgreSQL kills those after a bound and is a good safety net.

Q67 · Design. "Design a job queue table processed by twenty worker pods with JPA, with no job run twice and no worker starved."

Reveal answer

Strong answer Requirements: exactly one worker claims each job, workers never block each other, a crashed worker's job is eventually reclaimed, and throughput scales with the pod count.

Design: a job table with id, status (PENDING, RUNNING, DONE, FAILED), run_after, locked_at, locked_by, attempts, and an index on (status, run_after).

Each worker loops: in a short @Transactional method, run select j from Job j where j.status = 'PENDING' and j.runAfter <= :now order by j.runAfter with setLockMode(PESSIMISTIC_WRITE), setHint("jakarta.persistence.lock.timeout", -2) for skip-locked, and setMaxResults(10); set the claimed rows to RUNNING with locked_at and the pod name; commit.

Skip-locked means twenty workers each get a disjoint batch in one statement without waiting. Then process each job outside that transaction, and in a second short transaction mark it DONE or increment attempts and set run_after with backoff.

A sweeper resets RUNNING jobs whose locked_at is older than the job timeout, which handles crashed pods. Trade-offs: polling adds latency (mitigated by LISTEN/NOTIFY on PostgreSQL); the table needs periodic deletion of DONE rows.

What I would not do: claim jobs with optimistic locking, which under twenty workers is a retry storm, or hold the claiming transaction open during processing, which pins a connection per running job.

Land it FOR UPDATE SKIP LOCKED in a short claiming transaction is the whole trick; everything else is the bookkeeping that survives crashes.

Likely follow-ups
"Requirement change: jobs for the same customer must run one at a time, in order. What changes?"

The claim query gains a partition constraint.

Add a partition_key column, the customer id, and change the claim to select pending jobs whose partition has no RUNNING job: where status = 'PENDING' and run_after <= :now and not exists (select 1 from job r where r.partition_key = j.partition_key and r.status = 'RUNNING') order by run_after, still with FOR UPDATE SKIP LOCKED.

Two workers can still race on the same partition between the not-exists check and the update, so add a partial unique index on (partition_key) where status = 'RUNNING', which makes the second claim fail with a duplicate key that the worker treats as "skip".

Throughput becomes bounded by the number of distinct partitions with work, which is the correct consequence of the requirement.

"What would you cut under time pressure?"

The sweeper's automatic reset and the backoff logic.

Ship the claim query with SKIP LOCKED, the second transaction that marks DONE or FAILED, and a simple alert on jobs in RUNNING older than the timeout so a person resets them; that is a day's work and correct under normal operation.

Failed jobs get attempts + 1 and are re-queued immediately with no backoff, which is acceptable if failures are rare at launch.

What I would not cut is the two-transaction shape — claim, process outside the transaction, complete — because one long claiming transaction pins a connection per job and turns twenty workers into twenty held connections, which fails the first time processing is slow.

Nor SKIP LOCKED, because without it the workers serialise on the first pending row.

"A crashed worker's job is reset by the sweeper, but the original worker was not actually dead — just paused. Now it runs twice. Fix?"

A fencing token. Each claim increments a claim_token on the job row and the worker carries it; the completion UPDATE is where id = ? and claim_token = ?, so a stale worker finishing after a reset gets zero rows and knows to discard its result.

That prevents the stale completion from being recorded, but it cannot un-do side effects the stale worker already performed, so the job's work itself must be idempotent, keyed by job id, or must check the token before each external side effect.

Workers should also send heartbeats — update locked_at every thirty seconds — so the sweeper only resets jobs that are genuinely silent, and a worker whose heartbeat fails stops processing.

This is the same problem as distributed leases, and the answer is the same: a monotonic token checked at the point of write.

"Why not just use a message broker?"

Often you should, and I would say so. A broker gives you delivery, retries, dead-lettering and back-pressure without a polling loop, and Kafka or RabbitMQ handle far higher throughput than a table.

The table wins in three cases: when the jobs must be created transactionally with business data and there is no outbox yet, so "insert order and enqueue job" is one commit; when the job needs rich queries — cancel all jobs for a customer, reschedule by priority — that brokers do not offer; and when the operational surface of a broker is not justified for a few thousand jobs a day.

For a system that already has Kafka, the job table becomes the outbox and the workers become consumers. The database queue is the right first version and a fine permanent one at modest scale.

Drill · Locking in production

This group tests whether you can read a deadlock or a lock-wait storm back to the mapping or the transaction shape that caused it.

Q68 · Scenario. "Deadlocks appear on order_line after a release that added a @ManyToMany between Order and Promotion. Nothing in the order_line code changed. Diagnose."

Reveal answer

Strong answer Symptom: deadlock victims on a table the release did not touch.

Evidence: the engine's deadlock report — PostgreSQL's log line "deadlock detected" with both statements, or MySQL's SHOW ENGINE INNODB STATUS latest deadlock section — will show one transaction holding locks on order_promotion join rows while waiting on order_line, and another in the opposite order.

Cause: the new many-to-many is a List (a bag), so any change to an order's promotions deletes and reinserts all its join rows; that changed the order of statements in the flush — collection removals now run before the line inserts in the action queue — so two transactions editing the same order acquire locks on order_promotion and order_line in different sequences depending on which collection they touched first.

A mapping change altered lock ordering on an unrelated table.

Fix: change the collection to a Set so promotion changes are single-row statements; add OPTIMISTIC_FORCE_INCREMENT or a PESSIMISTIC_WRITE on the order root at the start of any order edit so concurrent edits serialise on the parent row before touching children, which gives every transaction the same lock order.

Prevention: lock the aggregate root first in every write path — one row, one order of acquisition — and run the deadlock-prone flow under a concurrency test before release.

Land it Deadlocks are about acquisition order, and a mapping change can reorder the flush — lock the root first and the order becomes deterministic.

Likely follow-ups
"You changed it to a Set and locked the root, and deadlocks continue but now between order_line and promotion. Next?"

Then a foreign key is involved.

Inserting an order_promotion row takes a share lock on the referenced promotion row on PostgreSQL — FOR KEY SHARE — and on InnoDB a shared record lock; a concurrent transaction updating that promotion row, say the marketing job adjusting a discount, takes an exclusive lock and waits for the share to clear, while holding locks the order edit needs.

Locking the order root serialises order edits with each other but not with the promotion job. The report will show the promotion update as one participant.

Fixes: the promotion job updates in tiny transactions and never touches order tables; or it only updates non-key columns, which on PostgreSQL does not conflict with KEY SHARE; or the order side references promotions by id value without a database foreign key, which trades integrity for isolation.

"How do you read a PostgreSQL deadlock report?"

The log line is "deadlock detected", followed by "Process 123 waits for ShareLock on transaction 456; blocked by process 789" and the reverse, then "Process 123: <statement>" and "Process 789: <statement>", and a HINT. The two statements are the ones that were waiting when the cycle closed, not necessarily the ones that took the first locks, so I reconstruct each transaction's full sequence from the application log using the request id, and write the two sequences side by side to find where they acquire the same rows in opposite order. The lock type — tuple, transaction id, or relation — tells whether it is a row conflict or something like a table-level lock from a DDL statement. log_lock_waits = on with deadlock_timeout = 1s makes long waits appear too, which often reveals the pattern before the first deadlock.

"Is locking the root row on every edit not just a global lock in disguise?"

It is a per-aggregate lock, which is what an aggregate is: one order's edits serialise, different orders proceed in parallel. That is the granularity the domain wants, because concurrent edits to the same order need to see each other anyway.

The cost is that an edit to one line waits for a concurrent edit to another line of the same order, which is a few milliseconds if transactions are short.

Where it becomes a global lock is when the "root" is a single shared row — a tenant record or a settings row — locked by every request; that is Q69's convoy.

So the rule is to lock the smallest row that represents the consistency boundary, and to measure lock waits on it; if waits appear, either the boundary is too big or the transactions are too long.

"How would you have caught the lock-order change before release?"

With a concurrency test on the aggregate's write paths, run in CI: two threads editing the same order along different paths — one adding a promotion, one adding a line — with barriers to ensure both hold their first locks before either commits.

Under the bag mapping it deadlocks reliably on Testcontainers PostgreSQL. It takes an hour to write and runs in seconds, and it should be a template every aggregate gets.

The other net is a mapping-contract test that asserts the statement sequence for "add a promotion", which would have shown the delete-all-and-reinsert pattern in the pull request.

Neither needs load; deadlocks are about order, not volume, and two threads are enough to prove the order is wrong.

Q69 · Scenario. "A stock-decrement endpoint uses PESSIMISTIC_WRITE and works fine at 50 requests per second, but at 500 the p99 goes to 3 seconds and the database shows hundreds of lock waits on ten product rows. Options?"

Reveal answer

Strong answer Symptom: a lock convoy on a few hot rows. Evidence: pg_stat_activity or information_schema.innodb_lock_waits shows many sessions waiting on the same ten product ids; transaction duration under the lock, not lock acquisition, explains the queue.

Causes: the lock is held for the whole transaction, and the transaction does more than the decrement — perhaps a payment call or an order INSERT — so each waiter pays for everything the holder does.

Options, ranked: one, shrink the critical section — do the decrement as the last statement of a transaction that contains nothing else, or as an atomic update stock set qty = qty - ? where product_id = ? and qty >= ? with the update count checked, which holds the row lock for microseconds and needs no SELECT FOR UPDATE at all; two, move the remote calls out of the transaction (Q33); three, shard the hot counter — ten sub-rows per product summed on read, or a reservation ledger appended per request and reconciled — so the hot row is no longer one row; four, absorb bursts in a queue and apply decrements serially by product.

A retry with backoff on LockTimeoutException bounds the wait. What not to do: switch to optimistic locking, which turns waits into a failure storm at this contention level.

Land it A pessimistic lock scales with how little you do while holding it — make the decrement one atomic statement and the convoy disappears.

Likely follow-ups
"They made the decrement one atomic statement and the p99 is still two seconds. What next?"

Then the lock is short but the transaction around it is not.

An atomic UPDATE holds the row lock from the moment it executes until commit, so if the method runs the decrement first and then inserts the order and writes the outbox, every waiter pays for those later statements.

Move the decrement to be the last statement before commit.

If it is already last, check what else is inside the transaction with a query-count log and the idle in transaction state in pg_stat_activity; a remote call or an afterCommit hook mistakenly running before commit are the usual suspects.

If the transaction really is only the decrement, the database itself is the bottleneck on that page — ten rows updated five hundred times a second is fine on PostgreSQL, so at that point I would suspect a trigger, a bloated table with many dead row versions, or synchronous replication latency.

"How does the sharded counter work, and how do you read the total?"

Instead of one row per product, keep ten rows per product — stock_shard(product_id, shard, qty) — and have each request decrement a random shard with the same atomic statement, update stock_shard set qty = qty - ? where product_id = ? and shard = ? and qty >= ?; if that shard has too little, try another.

Contention drops by the shard count. The total is select sum(qty) from stock_shard where product_id = ?, ten rows, trivially fast.

The catch is oversell: a request that needs three units when the shards hold one each cannot be satisfied even though the total is ten, so a fallback rebalances shards under a product-level lock, which is rare.

This is the same trick as PostgreSQL's own approach to hot counters and Java's LongAdder, and it is worth it only for genuinely hot products.

"What would the queue-based option look like, and what does the user experience become?"

The endpoint stops decrementing directly: it writes a reservation request — to a table or a Kafka topic keyed by product id — and returns 202 Accepted with a reservation id.

A single consumer per product key applies decrements serially with no contention at all, at thousands per second for one row, and records the outcome. The client polls or receives a push when the reservation is confirmed or rejected.

The experience changes from "you have it" to "we are holding it", which many shops already show as a spinner for a second.

It also gives natural back-pressure: a flash sale produces a queue, not a lock convoy, and the queue depth is a metric you can alert on. The cost is the asynchronous contract and the consumer's own failure handling.

"Why is switching to optimistic locking wrong here — is it not lock-free?"

It is lock-free in the sense that nobody waits, and that is exactly the problem at this contention.

Five hundred requests per second on ten rows means dozens of concurrent load-modify-save attempts per row; each commit invalidates the others, so most attempts fail and retry, and the retries multiply the load on the same rows until throughput collapses — the Q64 arithmetic.

Pessimistic waiting at least makes progress in order, one commit per lock hold. Optimistic locking is right when conflicts are rare, roughly under a percent of writes; a stock counter under a flash sale is the opposite.

The atomic statement is the best of both: no version, no wait beyond the microseconds of the UPDATE itself, and a definitive result from the update count.

Q70. "Optimistic lock with a timestamp @Version versus an integer — is there any reason to prefer the timestamp?"

Reveal answer

Strong answer Almost never. An integer (or long) version is incremented by exactly one per update, is immune to clock behaviour, costs four or eight bytes, and compares exactly.

A timestamp version (Instant or LocalDateTime) is set to the current time on each update, so two updates within the clock's resolution — a millisecond on most drivers, a microsecond on PostgreSQL — can produce the same value and let a conflict through, and a clock that steps backwards after a synchronisation can make a newer version look older.

The one argument for a timestamp is that it doubles as a free "last modified" field readable by humans and other systems; the counter-argument is that Spring Data's @LastModifiedDate provides that without weakening the lock.

Hibernate also supports @OptimisticLocking(type = ALL) or DIRTY with @DynamicUpdate, which compare every column or every changed column in the WHERE clause instead of a version — useful for legacy tables you cannot add a column to, at the cost of a wide WHERE clause and no protection for detached edits across transactions unless the whole state is carried along.

Land it An integer version is exact and clock-proof; use a separate audited timestamp for humans.

Likely follow-ups
"What happens when the integer version overflows?"

It wraps.

Hibernate increments an Integer version with plain addition, so after 2,147,483,647 updates the next value is negative, and the check still works because it compares equality, not order — a row with version -2,147,483,648 updated by a transaction that loaded it at that value succeeds.

Wrapping only causes a false match if a stale client holds a version from exactly 4.3 billion updates ago, which is not a realistic failure.

A row updated a thousand times a second takes 25 days to wrap an int and 290 million years to wrap a long. So Integer is fine; I use Long where the column type is already bigint to avoid a pointless mismatch in schema validation.

"How does the version get carried through a DTO and back, safely?"

The read DTO includes the version, and the API exposes it as an ETag header — ETag: "7" — with the write accepting If-Match. The service loads the entity and compares before applying.

The version must never be a field the client can set to bypass the check; a client that always sends the latest version by re-reading first is not bypassing anything, it is just losing the protection it was offered, which is its choice.

Spring provides ShallowEtagHeaderFilter for content-based ETags, but for a versioned resource I set the header explicitly from the entity's version, because it is cheaper and semantically exact. Spring Data REST does this automatically for @Version entities, which is a good reference implementation of the pattern.

"When would OptimisticLockType.ALL or DIRTY actually be the right choice?"

On a legacy table shared with other systems where you cannot add a column, and where conflicts must still be detected.

ALL puts every loaded column's old value into the UPDATE's WHERE clause; DIRTY puts only the changed columns' old values, which lets two writers change disjoint columns without conflict, at the price of missing conflicts on columns you did not change but depended on.

Both require @DynamicUpdate, produce long WHERE clauses, and struggle with floating-point and timestamp columns whose values do not round-trip exactly. Neither protects a detached edit across transactions unless the client sends back every old value.

So they are a bridge for legacy schemas, and I would still ask for the column.

"Can a version be updated by hand, or bumped without an update, for a 'touch' operation?"

Not by setting the field: Hibernate manages the version and ignores or rejects manual changes — setting it in code is overwritten at flush, and a mismatch with the snapshot can raise an exception.

To bump it deliberately without changing data, lock the entity with OPTIMISTIC_FORCE_INCREMENT, or run update versioned Order o set o.updatedAt = :now where o.id = :id in HQL, which increments the version in SQL.

Both are legitimate "touch" operations: they signal to other holders that the aggregate changed, which is how force-increment protects child edits in Q65.

What I would avoid is a native update orders set version = version + 1 outside Hibernate's knowledge while the entity is managed, because the in-memory version is then stale and the next flush fails confusingly.

Q71. "How do @Version and a bulk JPQL update interact, and what does 'update versioned' do?"

Reveal answer

Strong answer A bulk JPQL statement — update Order o set o.status = 'CANCELLED' where o.createdAt < :cutoff — is translated to one SQL UPDATE and does not go through the persistence context or the entity's UPDATE template, so it neither checks nor increments the version column.

Two consequences: a transaction holding one of those orders as managed will later succeed in its own versioned UPDATE, because the version in the database did not move, and silently overwrite the cancellation; and any client holding a detached copy is equally unaware.

Hibernate's extension update versioned Order o set ... adds version = version + 1 to the generated SQL, so the bulk change bumps every affected row's version and any concurrent versioned UPDATE then fails its check as it should.

It still does not update managed entities in memory, which is why @Modifying(clearAutomatically = true) remains necessary.

For deletes there is no versioned variant — a bulk delete simply removes rows, and a later versioned UPDATE on a deleted row fails with zero rows matched, which surfaces as an optimistic lock failure rather than a "not found", so handlers should expect that.

Land it Bulk updates skip the version unless you write "update versioned" — and they never touch what is already in memory.

Likely follow-ups
"Is 'update versioned' portable, and how do you write it through Spring Data?"

It is Hibernate HQL, not JPQL, so it is not portable to other providers — which is rarely a real constraint, since as of Aug 2026 almost every Spring Boot service runs Hibernate.

Through Spring Data it is simply @Modifying(clearAutomatically = true) @Query("update versioned Order o set o.status = :status where o.createdAt < :cutoff") int cancelOlderThan(...); Spring passes the string to Hibernate unchanged.

The generated SQL adds version = version + 1 to the SET clause, and for a timestamp version it sets the current time. The return value is the affected row count, which I log, because "cancelled 0 rows" is the usual symptom of a wrong cutoff.

Without the keyword, the same statement leaves the version untouched and the answer's silent-overwrite problem applies.

"What about bulk inserts with 'insert into ... select' — do they set a version?"

HQL's insert into Archive (id, status, version) select o.id, o.status, o.version from Order o where ... inserts whatever you select, so you must supply the version explicitly, typically 0 or the source's version; Hibernate does not add it.

If the version column is NOT NULL and you omit it, the INSERT fails.

The same applies to native inserts and to StatelessSession.insert(), which does write the entity's version field as-is — Hibernate seeds it to 0 for a null wrapper on a stateless insert as of 6.x.

So the checklist for any set-based write is: does the version column get a sensible value, and does any concurrent managed entity need to learn about it; the second question's answer is always "no, it cannot", which is why clearing or reloading follows.

"Why is a versioned UPDATE on a deleted row reported as an optimistic failure rather than not-found, and how do you handle it?"

Because Hibernate only has the update count to go on: zero rows matched can mean the version changed or the row is gone, and it reports the case it can name, StaleObjectStateException. The handler should reload by id after catching it.

If the reload finds a row, the conflict is real and the client gets a 409 with the current state; if it finds nothing, the resource was deleted concurrently and the client gets a 404 or 410.

Hibernate 6 and 7 do not distinguish them automatically, and Spring's translation to ObjectOptimisticLockingFailureException preserves the ambiguity. Envers or soft delete make the second case easier to explain to the user, because the deletion is visible as an event rather than as an absence.

"Does clearAutomatically fix everything, or is there still a stale-data window?"

It fixes the in-context staleness, but not other contexts.

Any other open transaction that loaded one of those orders before the bulk update still holds the old state, and its own versioned UPDATE will fail — correctly — because update versioned bumped the version; without the keyword it would overwrite.

Any detached copy held by a client, such as a form open in a browser, has the same fate.

So the window is exactly the set of entities loaded elsewhere before the bulk statement, and the only defence for them is the version check firing when they write.

That is the reason to always pair bulk updates with versioned on versioned entities, and the reason a conflict rate spike after a scheduled bulk job is expected and should be retried rather than alerted on.

Q72 · Scenario. "Two services on different codebases share one orders table. One uses JPA with @Version; the other does plain JDBC updates. Conflicts are being lost. What do you tell the second team?"

Reveal answer

Strong answer Symptom: JPA-side edits are overwritten by the JDBC service, and JPA never sees a conflict. Evidence: the JDBC service's UPDATE statements neither read nor bump version.

Cause: the version column is only a convention — the database does not enforce it — so a writer that ignores it can both overwrite JPA's changes and leave the version unchanged so that JPA's next versioned UPDATE succeeds against data it never saw.

The contract to give the second team: every UPDATE of the shared table must include version = version + 1 in the SET and and version = :expected in the WHERE, with the update count checked and a retry on zero — the protocol Hibernate follows.

If they cannot read-then-write, they must at least increment the version on every write so JPA's check fires.

Better: a database trigger BEFORE UPDATE that increments version whenever any column changes, which enforces the increment for every writer regardless of framework, leaving each writer responsible only for the WHERE check.

Best: stop sharing the table — one service owns writes and exposes an API, which is the E7 answer. Prevention: document the version protocol in the schema (a comment on the column), and an integration test that runs both writers concurrently.

Land it @Version is a protocol every writer must follow, and a trigger is how you make the database enforce half of it.

Likely follow-ups
"The second team says adding version checks to fifty hand-written UPDATEs is too much work. What is the minimum?"

The trigger, which is one migration and no application changes: create trigger bump_version before update on orders for each row execute function bump_version(), where the function sets NEW.version = OLD.version + 1 when any other column changed — comparing OLD.* IS DISTINCT FROM NEW.* excluding the version itself.

With that in place, every JDBC write bumps the version, so the JPA service's next versioned UPDATE fails instead of overwriting, and the JPA side's conflicts are no longer lost.

The JDBC side still overwrites JPA changes blindly, because it has no WHERE check; that half needs their code. But half the protocol enforced by the database is much better than none, and it also covers DBA sessions and migrations.

Hibernate's own UPDATE sets the version explicitly, so the trigger must not double-increment when Hibernate already did — the function checks whether NEW.version changed.

"How does the Hibernate side react when the trigger bumps the version by one and Hibernate also incremented it?"

If the trigger increments unconditionally, a Hibernate UPDATE that sets version = 8 from 7 is rewritten by the trigger to 9; Hibernate's in-memory entity now says 8 while the row says 9, and the next flush in the same transaction fails with a stale-state exception against Hibernate's own write.

The fix is in the trigger: only bump when NEW.version = OLD.version, which means the writer did not handle it. Then Hibernate's writes pass through untouched and JDBC writes get the increment.

I would test both paths in an integration test: a Hibernate update followed by a second Hibernate update in the same transaction must succeed, and a raw JdbcTemplate update must leave the version one higher than before.

"How would you detect lost updates that already happened?"

Compare writers' intentions with outcomes.

If both services log their writes with the row id, the old value they read and the new value they wrote, a query over the logs finds pairs where writer B's "old value" was not writer A's "new value" despite B writing after A — that is a lost update.

Without such logs, Envers on the JPA side gives revisions with values, and the JDBC side's writes appear as unexplained gaps between revisions, which a reconciliation can count.

For the future, a last_writer column set by each service, plus the trigger-maintained version, lets a nightly query count rows where the version advanced more than the number of recorded writes, which is a cheap lost-update detector across both codebases.

"What would the shared-table migration look like if the first team owned writes?"

Strangler-style. First, the JPA service exposes the write operations the JDBC service performs — usually three or four — as an API. Second, the JDBC service switches its writes to those calls behind a feature flag, keeping reads direct for now.

Third, database grants remove UPDATE and INSERT on orders from the JDBC service's role, so a regression cannot silently bring the direct writes back. Fourth, reads move to an API or a replicated read model, and the table becomes private. Each step is independently reversible.

The trigger from the first follow-up stays in place throughout as a safety net, and the lost-update detector from the previous answer measures progress: its count should drop to zero after step three.

Q73 · Design. "Design concurrency control for a collaborative document editor's metadata: title, tags, sharing settings, edited by several users at once through a JPA service."

Reveal answer

Strong answer Requirements: concurrent edits to different fields should both succeed, concurrent edits to the same field should be detected and surfaced to the user, no user should wait on another, and the API must carry enough for the client to resolve a conflict.

Design: optimistic control at the field-group level rather than the row level.

Split the metadata into small entities by change frequency and ownership — DocumentTitle, DocumentTags, DocumentSharing — each with its own @Version, sharing the document's primary key via @MapsId; a title edit then conflicts only with another title edit.

Each PATCH carries the version of the group it edits (an ETag in the API, per E6); the service loads, compares the client's version with the loaded one before applying (an explicit check, so the failure is a clean 409 before flush rather than an exception at commit), applies through domain methods, and lets the dirty check write.

Tags use a Set mapping with additive operations — add-tag and remove-tag endpoints rather than replace-all — so two users adding different tags never conflict.

Trade-offs: more tables and more versions to carry; the win is that lock scope matches what users perceive as "the same thing".

What I would not do: one wide document row with one version, which makes a tag change conflict with a title change and trains users to retry; or pessimistic locks, which hold a lock for a human's think time.

Land it Make the version's scope match the user's idea of a conflict — split the row by what changes together, and send the version back as an ETag.

Likely follow-ups
"Requirement change: the client wants a single GET that returns all metadata and a single PUT that updates any of it. How do the per-group versions survive?"

The GET returns all three groups with a version per group inside the body, and an ETag that is a composite — "t7-g3-s12" — so a client that only cares about one group can still use If-Match.

The PUT carries the composite; the service parses it, compares each group's version, and applies only the groups whose content changed, checking only those versions.

A PUT that changes the title while the tags moved underneath it succeeds, because the tags group is untouched; a PUT that changes tags after someone else changed tags gets a 412 with the current tags in the body.

The implementation is a small comparison loop in the service; the entities and their versions do not change. What changes is the contract, and that is worth a paragraph in the API documentation.

"What would you cut under time pressure?"

The split into three entities. One DocumentMetadata row with one @Version, the explicit version compare before applying, additive endpoints for tags, and a 409 response carrying the current state.

Users editing different fields at the same instant will occasionally see a conflict they consider spurious; the client can then retry automatically for the fields it changed by re-reading and reapplying, which is what most collaborative tools do under the hood.

I would keep the tags as a Set with add and remove endpoints from day one, because "replace all tags" is the operation that creates real lost updates, and I would keep the version in the ETag, because retrofitting conditional requests into clients is harder than splitting a table later.

"How do the @MapsId entities load — one query or three?"

Three by default, one per entity, if the service loads each group when needed — which is the point, since a title edit should load only the title row.

When the GET needs all three, a JPQL query with join fetch across the one-to-one associations loads them in one statement on the shared primary key, which is a cheap join.

Because the child entities share the parent's id through @MapsId, the associations from the parent side can be lazy proxies without the Q52 problem, provided optional = false is declared or the child rows are always created with the parent.

I would create all three rows in the same transaction as the document, so the invariant "every document has all three groups" is structural and the proxies are safe.

"Why not last-writer-wins with a timestamp, like many real editors?"

Because it loses work silently, and metadata is small enough that surfacing conflicts is cheap.

Editors that use last-writer-wins for document content do so with operational transforms or CRDTs underneath, which merge at the character level; for a title field there is no sensible merge between "Q3 plan" and "Q3 plan (draft)" and someone must choose.

The version-plus-412 design gives the user that choice with both values in front of them.

Where I would accept last-writer-wins is a field whose later value is by definition more correct — a "last opened at" timestamp — and I would exclude such fields from the version check entirely with @OptimisticLock(excluded = true) on the attribute, so touching them never causes a conflict.

Q74. "Explain how Hibernate's optimistic check behaves inside a JDBC batch, and the driver capability it depends on."

Reveal answer

Strong answer When hibernate.jdbc.batch_size is set and batch_versioned_data is true (the default since Hibernate 5), versioned UPDATEs of the same entity type are added to one PreparedStatement batch and sent with executeBatch().

The optimistic check normally reads the single update count, but in a batch the driver returns an int[] of update counts, one per statement, and Hibernate inspects each: any entry equal to zero means that particular row's version did not match, and Hibernate throws the stale-state exception naming the entity whose position in the batch had the zero.

That relies on the driver returning accurate per-statement counts rather than SUCCESS_NO_INFO (-2); PostgreSQL's and MySQL's drivers do — with one caveat: MySQL's rewriteBatchedStatements=true rewrites a batch of UPDATEs into multi-statement form and can still return per-statement counts, but older Connector/J versions returned aggregated counts for rewritten INSERTs, which is why the property was historically off for versioned data on some stacks.

If a driver cannot report counts, set batch_versioned_data: false and versioned updates execute one by one. The point of the question is that the version check is only as good as the update count, whichever path executes the statement.

Land it Batched or not, the optimistic lock is a zero in an update count — and a driver that cannot count per statement cannot batch versioned rows.

Likely follow-ups
"When one row in a batch of fifty is stale, what happens to the other forty-nine?"

They were sent in the same executeBatch(), so the database executed all fifty UPDATEs; forty-nine matched one row each and one matched zero. Hibernate inspects the returned counts, finds the zero, and throws StaleObjectStateException for that entity.

The exception propagates out of the flush, the transaction is rolled back, and all fifty updates are undone by the database.

So the outcome is atomic at the transaction level — none of the fifty persist — which is the correct behaviour for a unit of work.

The consequence for a batch job is that one stale row fails the whole chunk, which is why chunked jobs keep chunks small and retry the chunk, and why an import that touches rows users are editing should either lock them or run at a quiet time.

"How would you check what your driver returns for batched update counts?"

A ten-line JDBC test: prepare an UPDATE with a parameter, add three batch entries where one deliberately matches nothing, call executeBatch(), and print the int[]. pgjdbc returns {1, 0, 1}.

MySQL Connector/J returns the same with rewriteBatchedStatements=false, and with it true it still returns per-statement counts for UPDATEs because it sends them as separate statements in one packet; for rewritten multi-row INSERTs it returns SUCCESS_NO_INFO entries, which do not matter for versioning since inserts are not checked.

Oracle's driver returned -2 for everything before 12c, which is where Hibernate's batch_versioned_data flag came from. Hibernate itself calls Expectations.RowCount per position, and enabling org.hibernate.engine.jdbc.batch.internal=TRACE shows the counts it saw.

"Does batching change when the stale exception surfaces?"

Slightly. Without batching, each UPDATE runs and is checked immediately, so the exception is thrown at the first stale entity during the flush and no later statements run.

With batching, up to batch_size statements are queued and executed together, so the stale check happens when the batch executes — either when it fills, when the entity type changes and Hibernate switches batches, or at the end of the flush.

In both cases the exception is inside the flush and therefore inside the commit, so from the service method's point of view nothing changes: it surfaces from the transactional proxy.

The one visible difference is the exception's entity: with batching, Hibernate reports the entity at the zero position, which is not necessarily the first stale one in queue order if order_updates regrouped them.

"Are deletes also batched with version checks, and what about collections?"

Yes, versioned DELETEs batch the same way and are checked per position, with the same batch_versioned_data dependency.

Collection statements — join-table inserts and deletes, element collection rows — batch too but carry no version check, because those rows have no version; a concurrent change to a join table is detected only if the owning entity's version was bumped through force-increment, which is the Q65 point again.

One thing to know: Hibernate batches only consecutive statements with the same SQL, so an interleaved sequence of order updates and line updates produces many small batches unless order_updates=true is set.

The batch log at DEBUG shows the sizes, and a run of "Executing batch size: 1" lines is the sign that ordering is off.

Drill · Mapping judgment

This group tests design judgment: which mapping to reach for, and which to refuse, when the requirement is a business one.

Q75 · Design. "Design soft delete for customers so that deleted customers disappear from every query but their orders remain queryable and their unique email can be reused."

Reveal answer

Strong answer Requirements: no physical delete (orders reference the customer and regulation may require retention), automatic filtering from ordinary queries, explicit access for support and audit, and email uniqueness among live customers only.

Design: Hibernate 6.4+'s @SoftDelete(columnName = "deleted", strategy = SoftDeleteType.DELETED) on Customer, which turns remove() into update customer set deleted = true and appends where deleted = false to every load, query and collection fetch of customers automatically, including through @ManyToOne from orders — so an order whose customer is soft-deleted sees a null or missing reference, which you handle by mapping @NotFound(IGNORE) or, better, by keeping the customer reachable through a separate @Filter-based design.

That second point is the trade-off: if orders must still resolve their customer, use Hibernate's @FilterDef/@Filter(name = "liveCustomers") enabled per session in a web interceptor instead of the global @SoftDelete, so admin sessions can disable the filter and the association from orders is unaffected.

Uniqueness: a partial unique index on PostgreSQL, create unique index uq_customer_email_live on customer (email) where deleted = false; on MySQL, a generated column that is email when live and NULL when deleted, with a unique index on it, since NULLs do not collide.

What I would not do: a deleted_at check hand-written into every repository method, which is one forgotten where away from leaking deleted customers into a mailing list.

Land it Filter at the mapping level so no query can forget, and make the unique index partial so "deleted" really means gone.

Likely follow-ups
"Requirement change: a deleted customer's orders must still show the customer's name. Which design survives?"

The @Filter design, or a snapshot. With global @SoftDelete on Customer, Hibernate adds deleted = false to the join when an order's @ManyToOne customer is resolved, so the reference fails or returns nothing; there is no per-association opt-out as of Aug 2026.

With @FilterDef and @Filter, the filter applies to queries and collection loads where you enable it, but not to to-one association resolution, so order.getCustomer().getName() works for a deleted customer while customerRepository.findAll() hides them.

The alternative that survives any design is denormalising the customer name onto the order at creation time, as the shipping address snapshot does in Q54 — which the business may want anyway, since a customer renaming themselves should not rewrite old invoices.

"What would you cut under time pressure?"

The support-access path and the MySQL generated-column trick if the database is PostgreSQL. Ship @SoftDelete(strategy = SoftDeleteType.TIMESTAMP) on Customer in Hibernate 7, the partial unique index on email where deleted_at is null, and a native query in a small admin repository for the rare "show me the deleted customer" case.

That is a day. What I would not cut is the partial unique index, because a global unique index on email makes re-registration impossible and forces the team into "append a suffix to the deleted email" hacks that leak into exports.

And I would not hand-write where deleted_at is null into repository methods as a stopgap, because the stopgap becomes permanent and one of them will be missed.

"How do you restore a soft-deleted customer, and what does Hibernate let you do?"

Hibernate's @SoftDelete has no restore API, and a soft-deleted entity cannot be loaded through the normal path at all, so restore is a native statement: update customer set deleted_at = null where id = ?, in a service method that first checks that the email is not now in use by a live customer — the partial unique index enforces it, so the UPDATE fails with a duplicate key if it is, which the service turns into a clear error. With the @Filter design, an admin session disables the filter, loads the entity, sets the flag through a domain method, and lets the dirty check write it. Either way the restore should write an audit row, and the tests should cover "restore when the email was reused" explicitly, because that is the case people forget.

"What does soft delete do to the unique constraint on MySQL, exactly?"

MySQL has no partial indexes, so the trick is a generated column: email_live varchar(255) generated always as (case when deleted_at is null then email else null end) stored with a unique index on it.

Live customers have their email in email_live and must be unique; deleted customers have NULL, and MySQL's unique indexes allow any number of NULLs.

Re-registering with a deleted customer's email inserts a live row whose email_live is the email, which does not collide with the deleted row's NULL. The entity does not map the generated column at all, or maps it insertable = false, updatable = false for validation.

MariaDB and SQL Server support filtered or partial indexes directly, so the trick is MySQL-specific.

Q76. "When would you deliberately map a database view or a read-only table as an entity, and what annotations make it safe?"

Reveal answer

Strong answer Mapping a view is right when a read model is used widely enough that a reusable entity with relationships pays off — an order_overview view joining orders, customers and totals that a dozen screens query with Specifications and paging.

To make it safe: @Immutable on the class, so Hibernate skips dirty checking and throws on any attempt to persist or update; @Subselect("select ...") if you would rather keep the SQL in Java than create a view, with @Synchronize({"orders","order_line"}) so AUTO flush knows which tables the subselect depends on; load it in readOnly transactions so no snapshot is kept; and give it an @Id that is genuinely unique in the view's rows, because a duplicated id makes the identity map collapse two rows into one object.

Do not map relationships from the view to writable entities with cascades, and do not put it in the second-level cache unless the underlying tables are also cache-invalidated.

The alternative — a projection query into a record — is lighter when the read model is used from one or two places, and is what I would reach for first; the view entity earns its place when the read model needs the repository ecosystem.

Land it @Immutable plus a real unique id makes a view a safe entity; without those, it is a mutable object pretending to be a row.

Likely follow-ups
"What happens if a query against the view entity runs after an unflushed change to the underlying orders table in the same transaction?"

That is exactly the case @Synchronize exists for. Hibernate's AUTO flush mode decides whether to flush before a query by comparing the tables the query touches against the tables of the entities that are dirty in the persistence context.

A view or a @Subselect has no table of its own, so without @Synchronize({"orders", "order_line"}) Hibernate sees no overlap, skips the flush, and the view query returns the pre-change rows.

With the annotation, Hibernate treats a dirty Order as a reason to flush first, so the view sees the new totals.

I would verify it with a test that persists an order, queries the view in the same transaction, and asserts the total is present; that test fails the day someone drops the annotation.

"Why insist on a genuinely unique id? What actually goes wrong with a duplicated one?"

Hibernate keeps one Java object per entity type and id in the persistence context, which is the identity map.

When a result set yields two rows with the same id, the second row is not turned into a second object; Hibernate finds the existing instance in the map and returns that same reference again.

So a view that joins orders to lines and exposes the order id as the entity id returns, for an order with five lines, five references to one object holding the first line's values. The other four lines are silently lost.

The symptom in production is totals that are too small and lists that look deduplicated.

The fix is to give the view a real row identity, for example a composite of order id and line number as an @EmbeddedId, or to expose the line id as the key.

"Could you make the view entity writable through an INSTEAD OF trigger instead of marking it immutable?"

Technically yes, on PostgreSQL an INSTEAD OF trigger on the view can translate an UPDATE into writes to the base tables, and Hibernate would happily issue the UPDATE. I would refuse it in a code review.

The problem is that Hibernate's dirty check and optimistic locking assume the row it updates is the row it read, and a view row is derived from several rows with their own version columns.

A concurrent change to the base table would be invisible to the view's update path, so lost updates become possible with no OptimisticLockException to warn you.

It also hides the write model behind a read model, which is the opposite of the separation the view was introduced for. If the screen must edit, it edits the aggregate through its own repository and the view refreshes on the next read.

"How would you handle the situation where the view needs to be changed and the entity mapping is deployed across a rolling release?"

A view is schema, so it goes through the same expand-and-contract discipline as a table. Adding a column to the view is safe first: the migration uses CREATE OR REPLACE VIEW with the extra column, old pods ignore it, new pods map it.

Removing or renaming a column is the dangerous direction, because old pods still select it by name in their generated SQL and fail with an undefined-column error mid-rollout.

So the order is: add the new column to the view, release code that reads it, then release code that no longer reads the old column, then drop it from the view.

On PostgreSQL CREATE OR REPLACE VIEW can only append columns, so a reorder or a type change needs a drop-and-create inside a single migration transaction, which is fine because it is a metadata operation and takes a brief lock.

Q77 · Design. "A legacy table has a composite primary key (tenant_id, order_no). Design the JPA mapping and say what breaks compared with a surrogate id."

Reveal answer

Strong answer Requirements: map the existing key without changing the schema, keep relationships from child tables working, and avoid the identity-map problems of composite keys.

Design: an @Embeddable record OrderKey(Long tenantId, Long orderNo) used with @EmbeddedId — records are embeddable in Jakarta Persistence 3.2, and their value-based equality is exactly what a composite key needs, since Hibernate keys the identity map by equals and hashCode of the id object.

Child entities reference the parent with @ManyToOne @JoinColumns({@JoinColumn(name="tenant_id", referencedColumnName="tenant_id"), @JoinColumn(name="order_no", ...)}), and if the child's own key includes the parent's, @MapsId on the association maps the shared columns once.

What breaks: no @GeneratedValue — the application must assign order_no, typically from a per-tenant sequence or counter row; every foreign key is two columns, so indexes and joins are wider; Spring Data's isNew() cannot use a null id, so implement Persistable or accept the merge SELECT; findAllById becomes an OR of pairs rather than an IN list; and JOIN FETCH deduplication relies on the key record's equality being correct.

Trade-offs: the composite key keeps tenant isolation visible in every index, which is a real benefit for multi-tenant queries.

What I would not do: add a surrogate id as a "fix" without also keeping the composite unique constraint — the old key is the business identity, and the surrogate would just be a third column that nothing joins on.

Land it EmbeddedId as a record, MapsId on children, and application-assigned numbering — composite keys work, they just cost an id generator and a Persistable.

Likely follow-ups
"How exactly do you generate order_no per tenant without a race under concurrent inserts?"

Three honest options.

The cheapest correct one is a counter row per tenant in a tenant_counter table, incremented with a single atomic statement such as UPDATE tenant_counter SET next_no = next_no + 1 WHERE tenant_id = :t RETURNING next_no, executed in the same transaction as the insert.

The row lock serialises concurrent inserts for one tenant, which is usually what the business wants for a gap-free number, and tenants never contend with each other.

The second option is a database sequence per tenant, which is gapless-free but scales badly past a few thousand tenants because every sequence is a catalog object.

The third is a global sequence with the tenant id as a prefix, which is contention-free but does not give per-tenant numbering.

I would pick the counter row and put the increment in a small @Modifying query in the repository, so the entity never has to know.

"Why implement Persistable, and what does Spring Data do without it for an entity with an assigned key?"

Spring Data's SimpleJpaRepository.save() asks isNew() to decide between persist() and merge(). The default implementation answers "new" only when the id is null or a primitive zero.

A composite key is set by the application before save, so the entity is never considered new, and every save goes through merge().

Merge first issues a SELECT by the composite key to see whether the row exists, then copies state onto a managed instance, then inserts.

For a bulk import that is one extra round trip per row, and it also defeats JDBC batching because the SELECTs interleave with the INSERTs.

Implementing Persistable<OrderKey> with an isNew() backed by a transient boolean flag, cleared in @PostPersist and @PostLoad, tells Spring Data to call persist() directly and the SELECT disappears.

"The team says composite keys are always wrong and wants a surrogate id. Where do you push back and where do you agree?"

I agree that for a new table I would give it a surrogate BIGINT sequence id, because generated ids make Spring Data, batching, and foreign keys simpler and every performance author says so. I push back on the "always" for a legacy table.

The composite key is the business identity that every existing report, foreign key, and downstream system joins on. Adding a surrogate does not remove that fact; it just adds a third column.

If we add one, the composite unique constraint must stay, so the table has two candidate keys, and the child tables still carry the two-column foreign key until each one is migrated.

The migration of six child tables is the Q137 shape of project, weeks of work. The honest answer is: keep the composite key, map it well, and add a surrogate only when a concrete feature needs it.

"What goes wrong if OrderKey's equals and hashCode are subtly wrong, and how would you catch it in a test?"

Hibernate uses the key object as the map key in the persistence context and in the second-level cache.

If equals compares only orderNo and ignores tenantId, two different tenants' orders with the same number collapse into one map entry, and a load for tenant B returns tenant A's managed object, which is a cross-tenant leak, not a performance bug.

If hashCode is unstable, for example computed from a mutable field, a join fetch stops deduplicating and collections gain duplicates. A record makes this hard to get wrong because both methods are generated from all components.

The test I write is simple: persist two orders with the same orderNo under two tenants in one transaction, clear the context, load both by key, and assert they are different instances with the right tenant id. An EqualsVerifier test on the key class catches the structural mistakes.

Q78 · Scenario. "A bidirectional relationship causes StackOverflowError when an entity is logged or serialised. Explain and fix at the right layer."

Reveal answer

Strong answer Symptom: StackOverflowError from toString(), hashCode(), or Jackson serialisation. Evidence: the stack trace alternates between Order.toString and OrderLine.toString (or the Jackson serialisers for each).

Cause: Lombok's @Data or a generated toString/hashCode includes the collection, each line includes its order, and the recursion never ends; with Jackson, serialising the order walks into lines and back.

A second, quieter cost is that hashCode over the collection initialises the lazy list — an N+1 from a log statement.

Fix at the entity layer: write toString by hand with the id and a few scalar fields, exclude relationships (@ToString.Exclude, @EqualsAndHashCode.Exclude if Lombok stays), and use the id-based equals/hashCode from the primer.

Fix at the API layer: stop serialising entities — map to a record DTO inside the transaction. If entities must be serialised for a while, @JsonIgnore on the back reference or @JsonManagedReference/@JsonBackReference stop the cycle, but that is treating the symptom.

Prevention: ban @Data on entities in the style guide — @Getter plus hand-written identity methods — and an ArchUnit rule that controllers do not return @Entity types.

the bidirectional StackOverflowErrorruns offline
// Order has List<OrderLine>; OrderLine has Order. Serialising either one
// recurses for ever: order -> lines -> order -> lines -> ...
// Same for a naive toString(), and for equals/hashCode that walk the graph.

// FIX 1 — THE REAL FIX: do not serialise entities. Map to a DTO.
public record OrderDto(Long id, String status, List<LineDto> lines) {
    static OrderDto from(Order o) { ... }        // the cycle simply does not exist
}
// This also fixes lazy-loading during serialisation and stops the API contract
// being coupled to the schema. Everything below is a workaround for not doing this.

// FIX 2 — Jackson annotations, if entities must be serialised.
@JsonManagedReference        // on the parent's collection: serialised
private List<OrderLine> lines;

@JsonBackReference           // on the child's parent field: OMITTED
private Order order;

// or, to keep the reference as an id rather than dropping it:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

// FIX 3 — toString() must never traverse an association. Include the foreign
// key, not the object:
@Override public String toString() {
    return "OrderLine[id=" + id + ", orderId=" + (order == null ? null : order.getId()) + "]";
}
// A generated toString() that includes `order` both recurses AND triggers a
// lazy load -- which is how a debug log statement causes an N+1 and an
// exception in production.

The toString() case deserves the emphasis. An IDE-generated toString on a bidirectional entity will both recurse and force lazy loads, so simply adding a debug log line can produce N+1 queries and a LazyInitializationException in code that was otherwise correct.

Land it The cycle is in the mapping by design; the bug is generated code that walks it — write identity methods by hand and serialise DTOs.

Likely follow-ups
"Why is it wrong to include the collection in hashCode even if there were no cycle?"

Two reasons beyond the recursion.

First, the hash of a persistent collection depends on its contents, and the contents change as lines are added, so an Order placed in a HashSet before adding a line cannot be found afterwards; the set now contains an object at the wrong bucket.

Second, calling hashCode touches the collection, which initialises the lazy proxy. A log statement or a debugger watch on a detached order then throws LazyInitializationException, and inside a session it issues a SELECT for every order whose hash is computed.

That is an N+1 caused by logging. The id-based implementation avoids both: hash on the class, or on a constant, so the value never changes across the lifecycle, and compare by id when both ids are non-null.

"The API is public and cannot change this sprint. What is the least bad way to keep serialising entities safely for a few weeks?"

Keep the cycle from Jackson without changing the mapping. Put @JsonIgnore on every back-reference, the @ManyToOne pointing up to the parent, which stops the walk in one direction.

Register the jackson-datatype-hibernate6 module (the artifact name still says 6 for Hibernate 7 as of Aug 2026) so uninitialised proxies serialise as null instead of throwing or triggering loads, and set spring.jpa.open-in-view: false so any remaining lazy access fails loudly in tests rather than issuing queries from the serialiser.

Then add an assertSelectCount test per endpoint so the statement count is pinned. That buys the weeks.

The real fix, DTO records built inside the transaction, is scheduled and the ArchUnit rule that fails on @Entity return types is added with an exclusion list that shrinks each sprint.

"Where would you put the ArchUnit rule, and what exactly does it assert?"

It lives in the test source set as a normal JUnit test using @AnalyzeClasses over the application package. The rule reads: no method in a class annotated with @RestController may have a return type, or a return type's generic parameter, annotated with @Entity.

A second rule says classes annotated with @Entity must not be annotated with Lombok's @Data, @EqualsAndHashCode, or @ToString, because those are the generators that walk the graph.

A third says fields of @Entity classes must not appear in classes annotated with @Component that are singletons, which catches the Q119 leak. The rules run on every build in a few hundred milliseconds.

I prefer them to a style-guide document because they fail the pull request rather than relying on a reviewer noticing.

"Does the same StackOverflowError happen with equals in a Set, and how does that interact with Hibernate's PersistentSet?"

Yes, and it is nastier. PersistentSet wraps a HashSet, and adding an element calls hashCode and equals on the element. If OrderLine.equals includes its order field and Order.equals includes its lines, the first lines.add(line) recurses.

Even without the cycle, a Lombok equals over all fields means an unsaved line with a null id and identical fields equals another unsaved line, so the set silently drops the second one.

The id-based rule handles both: equality is by id when both are set, and by reference when either is null, and hash is a constant per class.

Two loaded lines are distinguished by id; two new lines are distinct until they are saved, and the constant hash keeps them findable after the id is assigned.

Q79. "What does @Immutable buy you on an entity that is genuinely never updated, and what happens if someone updates it anyway?"

Reveal answer

Strong answer @Immutable tells Hibernate the entity's state never changes after insert.

Hibernate then skips the snapshot and the dirty check for those entities in every flush — the same saving a read-only transaction gives, but per entity type and in write transactions too — which matters for reference data loaded alongside writable entities: a report that loads 50,000 immutable ExchangeRate rows in a transaction that also updates ten orders no longer pays 50,000 field comparisons at every flush.

Immutable entities are also ideal second-level cache candidates with CacheConcurrencyStrategy.READ_ONLY, the cheapest strategy, because no invalidation logic is needed.

If code changes a field on an immutable entity, Hibernate silently ignores the change — no UPDATE is generated and no exception is thrown by default, which can hide a bug; set hibernate.session.immutable_entity_update_query_handling_mode: exception (or the annotation's strictness in Hibernate 6.x and 7) to make a bulk update against an immutable type fail instead.

Deleting an immutable entity is allowed. Combine it with @Cache(READ_ONLY) and a final-style class with no setters, so the Java side matches the promise.

Going deeper The property that makes bulk statements against immutable types fail is hibernate.query.immutable_entity_update_query_handling_mode, with values warning (the default) and exception. It governs JPQL and criteria bulk update and delete statements only.

Changing a field on a managed immutable instance is a separate path: Hibernate skips the dirty check for the type entirely, so the change is never seen and never written.

No property turns that into an exception; the protection is in the Java class, which is why the class should have no setters and be built through a constructor.

To verify the setting works, write a test that runs update ExchangeRate r set r.rate = 1 and expects HibernateException with the message naming the immutable entity.

Land it Immutable means "never dirty-check me" — a free performance win for reference data, with the caveat that accidental changes vanish silently unless you make them fail.

Likely follow-ups
"What does @Immutable change in the flush algorithm, concretely, and how would you measure the saving?"

At flush, Hibernate walks every entry in the persistence context and, for entities whose persister reports them as mutable, compares each property value against the snapshot array taken at load.

For an @Immutable type the persister answers that the entity is not mutable, so the entry is skipped without touching its fields and no snapshot is stored when it is loaded, which also halves the memory per row.

The saving is proportional to rows loaded times columns times flushes.

I would measure it with Hibernate statistics: getFlushCount() and the flush time visible in the session metrics log at org.hibernate.stat DEBUG, before and after adding the annotation to the reference type, on a transaction that loads 50,000 rates and updates ten orders.

On a laptop that scenario drops from tens of milliseconds per flush to under one.

"What if the reference data really does change once a quarter? How do you update it?"

The quarterly update is an administrative operation, so it does not go through the entity.

It runs as a Flyway repeatable migration or a small admin job that issues plain SQL, or a JPQL bulk statement in a service that has the handling mode set to allow it.

After the write, the second-level cache region for the type must be evicted on every node, with sessionFactory.getCache().evictEntityData(ExchangeRate.class), because READ_ONLY regions never expire entries on their own.

In a multi-pod deployment that means a broadcast, which is the Q107 problem, so I would put a short time-to-live on the region as a safety net even for read-only data. The Java class stays without setters.

A quarterly change is not a reason to make every flush pay for a mutable type.

"Does @Immutable on a collection mean the same thing as on the entity?"

No, it is a separate annotation target with a different rule. @Immutable on a @OneToMany or @ElementCollection field tells Hibernate the collection membership never changes after load: no adds, no removes.

Hibernate then skips the collection's dirty check and, importantly, throws HibernateException with "changed an immutable collection instance" at flush if code did add or remove an element, so the collection case is loud where the entity case is silent.

The elements themselves may still be mutable entities. It is useful for a history list on an aggregate that is appended to only through a separate repository, so nobody can cascade a delete through it by accident.

I use it rarely, because the same protection comes from not exposing the mutable list from the entity.

"How does @Immutable interact with @Version and optimistic locking?"

An immutable entity has no reason to carry a version column, because no UPDATE is ever generated for it, and Hibernate does not increment or check anything on it.

If a legacy table has a version column, map it as a plain field or leave it unmapped rather than as @Version, so that Hibernate does not try to include it in the insert logic for a type it will never update.

Where version matters is on the aggregate that references the immutable type.

An order that points at an exchange rate carries its own version, and replacing the reference with a different rate is a change to the order's foreign-key column, detected and versioned on the order side. That is the correct place for the check.

Deletes of immutable rows go through, and the foreign key from orders will refuse them if they are still referenced.

Q80 · Design. "Design multi-tenancy for a SaaS orders service on JPA — one schema per tenant versus a tenant_id column — and how Hibernate supports each."

Reveal answer

Strong answer Requirements: no tenant can ever read another's rows, per-tenant data export and deletion must be feasible, the tenant count may reach thousands, and the operational cost must stay flat. Two designs.

Discriminator column: every table has tenant_id, every query is filtered, and Hibernate 6.0+ supports it natively with @TenantId on a field plus a CurrentTenantIdentifierResolver bean — Hibernate adds where tenant_id = ? to loads and queries and sets the column on insert, so application code never writes the filter.

Cheap to operate, one schema to migrate, thousands of tenants fine; the risk is a native query or a bulk update that forgets the filter, mitigated by PostgreSQL row-level security policies keyed on a session variable as a second wall.

Schema per tenant: MultiTenancyStrategy SCHEMA with a MultiTenantConnectionProvider that runs SET search_path per connection; strong isolation, per-tenant restore and export are trivial, but Flyway must migrate every schema on each deploy (thousands of schemas make deploys slow and metadata catalogues large), and cross-tenant analytics need a union.

Database per tenant is the same trade-off pushed further. Decision: discriminator with row-level security for a large tenant count with small tenants; schema-per-tenant for a few dozen large, regulated tenants.

What I would not do: rely on a @Filter enabled by a web interceptor as the only isolation, because a background job that forgets to enable it reads every tenant.

Land it @TenantId for the filter, row-level security as the wall, and schemas only when tenants are few and regulated enough to pay for it.

Likely follow-ups
"How does @TenantId actually get the tenant value, and what happens on a background thread with no request?"

Hibernate asks the CurrentTenantIdentifierResolver bean for the tenant when a session opens, and stores it on the session. Every load, query, and insert on a @TenantId entity then uses that value: added to the WHERE clause on reads and set on the column on inserts.

If an entity is loaded with a different tenant than the session's, Hibernate throws PropertyValueException rather than returning it. The resolver usually reads a ThreadLocal or a scoped bean set by a servlet filter from the JWT or a header.

On a background thread the resolver has nothing to return. The right behaviour is to throw, not to default, so the job either fails fast or explicitly sets the tenant it is working on before opening the transaction.

A resolver that returns a "system" tenant is how cross-tenant reads happen quietly.

"Row-level security is the second wall. How do you wire the PostgreSQL session variable through a Hikari pool safely?"

Row-level security policies compare each row's tenant_id to a session setting such as current_setting('app.tenant'). The application must set that variable on the pooled connection at the start of every transaction and clear it at the end, otherwise the next borrower inherits it.

The clean mechanism is SET LOCAL app.tenant = 'acme' issued as the first statement of the transaction, because SET LOCAL is scoped to the transaction and resets automatically at commit or rollback, so a returned connection carries nothing.

In Spring that is a TransactionSynchronization or a small aspect on the transactional entry point that runs a native statement through the current EntityManager.

The policy must also apply to the application role with FORCE ROW LEVEL SECURITY for table owners, and the migration role stays exempt. Verification is a test that sets tenant A, runs a native select count(*), and gets only A's rows.

"A big customer demands their own database. Can one deployment serve discriminator tenants and a dedicated database at the same time?"

Yes, but not with Hibernate's built-in multi-tenancy alone, and I would say that plainly. Hibernate supports one strategy per SessionFactory.

The way to serve both is a MultiTenantConnectionProvider that routes by tenant to a connection pool, with the large customer's tenant mapped to their dedicated database and every small tenant mapped to the shared database, while the discriminator filter still applies everywhere because the dedicated database simply has one tenant value in the column.

The costs are real: every migration runs against N plus one databases, the pool count grows per dedicated customer, and monitoring must be per database. I would cap the number of dedicated databases contractually and price it so that it stays rare.

The alternative, a separate deployment for that customer, is often simpler than a routing layer.

"What breaks in schema-per-tenant at two thousand tenants, specifically?"

Four things, in the order they hurt. Deploy time: Flyway runs the migration set per schema, and two thousand schemas times even a two-second migration is over an hour per release, so releases with schema changes need a parallel migration job.

Catalog size: PostgreSQL's pg_class and pg_attribute hold every table of every schema, so with fifty tables per tenant that is a hundred thousand tables, which slows planning, autovacuum's catalog scans, and backups.

Connection pools: SET search_path per checkout is cheap, but prepared-statement caches on the driver are keyed by SQL text, and the same text resolves to different tables per schema, so plan reuse across tenants is not just useless but wrong if the driver caches the server-side plan across a search_path change.

Operations: per-tenant restore is easy, but cross-tenant reporting is a two-thousand-way UNION. Past a few hundred tenants the discriminator model wins.

"How would you test that no query can ever leak across tenants?"

Three layers of test. A unit-level test per repository that seeds two tenants, sets the resolver to tenant A, and asserts every finder returns only A's rows, including native queries, which is where @TenantId does not apply.

A property-style integration test that runs the whole HTTP API for tenant A against a database where tenant B has strictly more data, and fails if any response contains a B identifier.

And a database-level test that connects as the application role with the row-level-security variable set to A and runs SELECT count(*) on every tenant table, comparing against the count for A alone.

The third test is the one that catches a forgotten filter in a new native query, because it does not depend on the ORM at all.

09 · DrillFetching, N+1, Caching & Performance — Q81–Q115

Performance is where a Hibernate interview stops being about annotations and starts being about numbers: how many statements, how many rows on the wire, how many objects in the heap, how many connections in the pool. These thirty-five questions cover lazy loading and every flavour of N+1, pagination and projections, JDBC batching and bulk work, the two caches, and the observability that lets you prove any of it. Most are scenarios, because that is how the topic is examined.

Drill · Lazy loading & N+1

This group tests whether you can find the N+1 from the symptoms, name the mechanism that caused it, and pick the fix that matches the access pattern.

Q81 · Scenario. "One endpoint issues 1,200 queries per request. The developer says 'I only call the repository once'. Walk me through diagnosis to fix."

Reveal answer

Strong answer Symptom: statement count proportional to result size.

Evidence: turn on org.hibernate.SQL and Hibernate statistics for one request, or use a datasource proxy that counts statements; the log will show one SELECT on the parent table followed by hundreds of near-identical SELECTs differing only in a bound id — the signature of lazy loading in a loop.

Identify which association from the child table name.

Ranked causes: one, a lazy collection or lazy to-one touched per element in a loop or by a mapper or serialiser — the classic N+1; two, an EAGER @ManyToOne that Hibernate resolves with a secondary select per row when the query did not join it (EAGER on a JPQL query is not a join, it is N extra selects); three, @Formula or an element collection loaded per parent.

Fix by access pattern: if the loop always needs the children, join fetch or an @EntityGraph on that query; if only sometimes, @BatchSize(50) or default_batch_fetch_size to make it N/50; if the endpoint only reads, a projection to a record that selects exactly the columns, which removes the association entirely.

Then map the EAGER to LAZY, because the EAGER variant cannot be fixed per query. Prevention: assertSelectCount in the endpoint's integration test and open-in-view: false.

Land it One repository call, twelve hundred statements — the loop is the query, and the fix is chosen by whether the loop always, sometimes, or never needs the children.

Likely follow-ups
"You added join fetch and the count went from 1,200 to 3. The endpoint is still slow. What next?"

Then the cost moved from round trips to row volume. A join fetch of two collections, or a collection with wide parents, multiplies rows on the wire: 200 orders with 30 lines each is 6,000 rows, each repeating every order column.

I would check the SQL log for the result size and the time per statement, and Hibernate's getEntityLoadCount() for how many objects were hydrated.

The fix is to trade one wide statement for two narrow ones: fetch the parents alone, then let @BatchSize(50) or a second join fetch ... where o in :orders query load the children without repeating parent columns.

If the endpoint is read-only, the better fix is the projection that removes the association entirely. I would also confirm the persistence context is not being flushed repeatedly by the loop, which getFlushCount() shows.

"How do you tell an N+1 from lazy loading apart from an N+1 from EAGER, just from the log?"

Timing and order. An EAGER to-one on a JPQL query fires its secondary selects immediately after the main query, before any application code runs, because Hibernate resolves the EAGER promise during hydration of the result set.

So the log shows the parent SELECT and then a burst of child SELECTs with no gap and no application log lines between them.

A lazy association touched in a loop shows child SELECTs interleaved with whatever the loop logs, spread over the request's duration, and only for the entities the loop actually reached.

With org.hibernate.orm.jdbc.bind at TRACE the bound ids confirm it: EAGER loads every distinct id from the result, a loop loads the ones the code visited. Hibernate statistics separate them too, since EAGER resolution counts as entity fetches during the query.

"What does the assertSelectCount test look like, and how do you keep it from being brittle?"

It uses the datasource-proxy library wrapped around the test datasource, with QueryCountHolder reset at the start of the test. The test calls the endpoint through MockMvc or a test client against Testcontainers PostgreSQL, then asserts SQLStatementCountValidator.assertSelectCount(2) and assertUpdateCount(0).

To keep it honest, the test seeds a realistic data shape, at least twenty parents with several children each, because an N+1 with one parent is invisible.

To keep it from being brittle, I assert an upper bound rather than an exact count where the query plan legitimately varies, and I put the assertion in a helper so the message names the endpoint.

It runs with open-in-view: false in the test profile, so the count reflects what the service layer does, not what the serialiser triggered.

"Which of the three fixes would you pick if the same repository method is used by three endpoints with different needs?"

Neither a global change to the mapping nor a join fetch baked into the shared method, because both make every caller pay for one caller's needs.

I would keep the repository method narrow and give each caller its own fetch plan: a named @EntityGraph variant of the method for the endpoint that always needs the children, @BatchSize on the collection as the default for the caller that sometimes needs them, and a projection method for the read-only list.

Spring Data supports several methods over the same JPQL with different graphs, and Hibernate 6 and 7 apply the graph as a fetch plan on top of the query. The interviewer wants to hear that the fetch strategy belongs to the use case, not the entity.

That is the whole reason to map lazy in the first place.

Q82. "Why is EAGER on a @ManyToOne worse than a lazy load you forgot to fetch — mechanically, in the SQL?"

Reveal answer

Strong answer Two reasons.

First, EAGER is unconditional: for em.find() Hibernate adds a join to the SELECT, but for a JPQL query it does not join — it runs the query, then issues one secondary SELECT per distinct customer to satisfy the EAGER promise, an N+1 you cannot turn off for that query without changing the mapping.

Every code path pays it, including paths that only needed the order id.

Second, EAGER compounds along the graph: if Order.customer is EAGER and Customer.address is EAGER and Address.country is EAGER, then finding one order loads four tables, and a query for 1,000 orders can issue thousands of secondary selects across three levels.

A lazy association you forgot to fetch costs the same N+1 on the one path that touches it, but it is fixable per query with join fetch, and the paths that never touch the customer pay nothing.

The only place EAGER is harmless is a to-one that is always needed and always loaded through find(), which is rare. Hibernate's own guidance and every performance author since 2012 agree: map lazy, fetch explicitly.

The JPA default of EAGER for to-one is a specification decision from 2006 that the industry has been working around ever since.

Land it EAGER is an N+1 you cannot opt out of per query; LAZY is one you can fix where it hurts.

Likely follow-ups
"You say map lazy on a @ManyToOne. What does Hibernate actually put in the field, and what can go wrong with it?"

Hibernate puts a runtime-generated subclass of the target entity, a proxy, created by ByteBuddy, which holds only the id and a reference to the session. Any method call other than getId() triggers the load. Three things go wrong.

The proxy's class is not Customer.class, so instanceof works but getClass() comparisons and switch over sealed subtypes fail, and an inheritance hierarchy returns a proxy of the declared type, not the concrete subclass, so a cast to PremiumCustomer throws.

Equality between a proxy and a real instance needs the id-based equals with Hibernate.getClass() or instanceof, not getClass(). And Jackson serialises the proxy's internal fields. Every one of those has a known fix; the EAGER mapping does not.

"Is there any case where EAGER on a to-one does not cause the secondary select on a JPQL query?"

Yes, when the query itself already joins the association with join fetch, or when the target is in the second-level cache, or when the same customer is already in the persistence context from earlier in the transaction.

In all three cases Hibernate finds the target without a new SELECT. But that is the point: the mapping is EAGER, so Hibernate must satisfy it somehow on every path, and only the paths that happen to have the data avoid the cost.

On a query that returns a thousand orders from a hundred customers, EAGER issues a hundred secondary selects, one per distinct customer, because the persistence context deduplicates.

It is fewer than a thousand, which is why people underestimate it, but it is still unbounded and unfixable per query.

"How do you migrate a large codebase from EAGER to LAZY without breaking production?"

Association by association, with a test net. First, turn on open-in-view: false in the test profile only and run the integration suite; failures show where the view layer depends on the EAGER data.

Second, flip one association to LAZY, run the suite, and fix each LazyInitializationException by adding a fetch to the query that path uses, an @EntityGraph or a join fetch. Third, add assertSelectCount to the endpoints touched so the statement count is now pinned lower than before.

Ship, watch the statements-per-request metric, repeat. The order matters: start with the associations on the hottest queries, where the secondary selects cost the most. Do not flip every association at once, because then every exception is ambiguous and the rollback is the whole change.

"Does the same argument apply to @OneToOne?"

Mostly, with one wrinkle. On the owning side of a @OneToOne, the one holding the foreign key, LAZY works the same way as on a @ManyToOne: Hibernate has the foreign-key value and can create a proxy for it.

On the inverse side, mapped with mappedBy, Hibernate cannot know whether the other row exists without querying, because a proxy for a possibly-null reference cannot be created honestly.

So the inverse side is effectively EAGER unless bytecode enhancement is on, and every load of the parent issues a SELECT for the child.

The fix is to avoid the inverse side, or to make the child share the parent's primary key with @MapsId, which lets Hibernate assume existence, or to map the association only from the owning side and query the other direction explicitly.

Q83 · Scenario. "Adding join fetch on two List collections in one query throws MultipleBagFetchException. The team wants both loaded. Options?"

Reveal answer

Strong answer Symptom: MultipleBagFetchException: cannot simultaneously fetch multiple bags at query build time.

Cause: fetching two bags (Lists without an order column) in one SQL join produces a Cartesian product — every line times every payment for each order — and because bags can contain duplicates Hibernate cannot tell which duplicates in the result are real and which are join artifacts, so it refuses.

Options, ranked: one, fetch the two collections in two queries in the same transaction — first select o from Order o join fetch o.lines where ..., then select o from Order o join fetch o.payments where o in :orders; the second query returns the same managed instances (identity map) with their second collection now initialised, and the total cost is two statements with no product; two, change one or both collections to Set, or add an @OrderColumn, so Hibernate can deduplicate — this permits the single query but the result set is still the product, so 50 lines times 20 payments is 1,000 rows per order on the wire, which is usually worse than two queries; three, fetch one with join fetch and leave the other to @BatchSize.

Never change to Set merely to silence the exception without thinking about the product size. Prevention: keep one collection fetch per query as a rule, and treat the exception as Hibernate protecting you.

Land it Two collections means two queries against the same identity map — the exception is Hibernate refusing to give you a Cartesian product it cannot untangle.

Likely follow-ups
"Why does the second query return the same managed instances rather than new ones?"

Because both queries run in the same persistence context, and Hibernate guarantees one Java object per entity id per context.

When the second query's result set arrives, Hibernate hydrates each row, looks up the id in the identity map, finds the Order instance loaded by the first query, and instead of creating a new object it attaches the freshly fetched payments collection to that existing instance.

The orders returned by the second query are therefore the same references the caller already holds, now with both collections initialised.

If the second query ran in a different transaction, or after a clear(), it would produce new instances with only payments loaded, and the caller's original objects would still have an uninitialised payments proxy. The rule is: same transaction, no clear, and the trick works.

"The team changed both to Set and the exception went away. The endpoint got slower. Why?"

Because the exception was protecting them from the row product, and Set only fixes the deduplication, not the volume.

An order with 50 lines and 20 payments joined in one statement produces 1,000 rows for that order, each carrying every column of the order, the line, and the payment.

A hundred orders is a hundred thousand rows over the wire, which Hibernate then has to walk and deduplicate into 100 orders, 5,000 lines and 2,000 payments by hashing. The two-query approach transfers 5,000 plus 2,000 rows.

I would show the difference with the row count in the SQL log or EXPLAIN ANALYZE, and put the two-query pattern back. Set is still the right type for an unordered collection, but the reason is correctness, not permission to join everything.

"How does @BatchSize change this picture, and when is it the better option than the second query?"

With @BatchSize(50) on payments, the first query fetches orders with lines, and the first touch of any order's payments loads payments for up to 50 orders in one IN-list statement.

For 100 orders that is two batch statements instead of one explicit second query, so slightly more statements but no code to write, and it applies to every path that touches payments, not only this one.

It is better when the caller does not always need the second collection, because nothing is loaded unless touched, or when the parents come from several queries.

The explicit second query is better when the caller always needs both and the parent count is large, because one where o in :orders statement scales to a page of any size while batches are N over 50 statements.

"What is a bag exactly, and why does Hibernate treat List differently from Set here?"

A bag is Hibernate's term for an unordered collection that allows duplicates, and it is what a plain java.util.List without @OrderColumn maps to, because a database table has no inherent order and Hibernate cannot promise list positions.

Since duplicates are legal in a bag, Hibernate cannot use element identity to tell a genuine duplicate from a row repeated by a join, so it refuses to fetch two bags at once.

A Set forbids duplicates by contract, so Hibernate deduplicates by equals and hashCode and is willing to fetch two. A List with @OrderColumn is an indexed list, and the index column tells Hibernate which row belongs at which position, so duplicates are recognisable by position.

The lesson is that the Java type is a promise to Hibernate about semantics.

Q84. "How does @BatchSize actually work, what SQL does it produce, and why does Hibernate 6 pad the IN list?"

Reveal answer

Strong answer When a lazy collection or proxy is initialised, Hibernate looks in the persistence context for other uninitialised collections of the same role — other orders' lines — and loads up to size of them in one statement: select ... from order_line where order_id in (?, ?, ..., ?).

Iterating 1,200 orders and touching each one's lines therefore costs 1,200 divided by 50, or 24 statements, instead of 1,200. The same mechanism applies to lazy to-one proxies through @BatchSize on the target entity class, and globally through hibernate.default_batch_fetch_size.

Hibernate 6 pads the IN list to a small set of fixed sizes — powers of two up to the batch size, then the batch size itself — repeating the last id to fill the slots, so that a batch of 37 uses the 64-slot statement rather than a unique 37-slot one.

The reason is statement caching: both the JDBC driver's prepared-statement cache and the database's plan cache key on SQL text, and fifty distinct IN-list lengths would mean fifty plans; padding keeps it to about six.

The older setting hibernate.batch_fetch_style is gone in 6 — padded is the only style. The trade-off against join fetch: one extra statement per batch, but no repeated parent columns and it composes with pagination.

Land it BatchSize turns per-parent loads into IN-list loads sized in powers of two, so the plan cache stays small and the N+1 becomes N/50.

Likely follow-ups
"Where does Hibernate find the other 49 ids to batch? What if they are not in the persistence context?"

From the persistence context only. When a collection is initialised, Hibernate looks at the BatchFetchQueue, which records every uninitialised collection of the same role belonging to entities currently managed in this session, and picks up to the batch size of them.

If only ten orders are loaded, the batch holds ten ids, padded to the next power-of-two slot with repeats. If the orders were loaded in a previous transaction, or detached, their collections are not in this session's queue and cannot be batched.

That is why batch fetching is a property of the session, not the mapping alone, and why a loop that loads each parent with findById in its own transaction never benefits: each session sees one parent.

The whole page of parents must be loaded before the first collection is touched.

"What batch size would you pick, and what is the cost of setting it too high?"

Between 20 and 100 is the useful range, and 50 is my default through hibernate.default_batch_fetch_size: 50. Higher sizes mean fewer statements, but three costs grow.

The IN list has a hard limit on some engines: Oracle refuses more than 1,000 expressions and SQL Server's parameter limit is around 2,100.

The database planner handles a very long IN list less well, sometimes falling back to a hash of the list rather than an index probe per value.

And padding wastes work: a batch of 130 with a size of 256 sends 126 repeated ids that the database dedupes but still parses.

Hibernate 6 and 7 cap a single IN list and split larger batches into multiple statements automatically, so the cost of an oversized setting is mainly plan quality. I set it, then look at the actual statements in the log.

"How does the padded IN list interact with PostgreSQL's plan caching and the prepareThreshold?"

The PostgreSQL driver counts executions per distinct SQL text and, after prepareThreshold executions, five by default, asks the server to keep a named prepared statement with a cached plan.

Padding keeps the number of distinct texts to roughly log base two of the batch size, so with 50 that is about six texts per collection role, and each one crosses the threshold quickly and gets a server-side plan.

Without padding there would be up to fifty texts, most never reaching five executions, so every execution would be parsed fresh.

The second-order effect is that after five executions the server may switch to a generic plan for the parameterised IN list, which is usually fine for a primary-key probe. If a role's plans look bad, plan_cache_mode = force_custom_plan on the session is the escape.

"Does batch fetching work for to-one proxies, and how is that configured differently?"

Yes. When a lazy @ManyToOne proxy is initialised, Hibernate looks for other uninitialised proxies of the same entity class in the session and loads them together with where id in (...).

The annotation goes on the target entity class, for example @BatchSize(size = 50) on Customer, not on the field, because the batch is per entity type. The global default_batch_fetch_size covers both collections and proxies.

This is the mechanism that makes a lazy to-one across a page of orders cost one or two statements instead of one per distinct customer, which is the answer to the EAGER problem in Q82: map lazy, batch by default, fetch explicitly when the query knows.

Q85 · Scenario. "A report loads 20 orders with join fetch on lines, and the SQL log shows 20 orders times 50 lines transferred, but then the JSON shows each order's line list duplicated five times. Explain."

Reveal answer

Strong answer Symptom: duplicated collection contents after a join fetch. Evidence: the query joins more than one collection or the collection is a bag fetched alongside another to-many path, and the entity's list length is a multiple of the true count.

Cause: the mapping uses a List without @OrderColumn — a bag — and the query joined a second to-many association (or the same collection twice via a Specification and an entity graph together), so each line row appears once per matching row of the other join.

Hibernate cannot deduplicate a bag's elements by identity, because a bag is allowed to hold the same element twice.

Hibernate 6 removed the old duplication of parents — you no longer need distinct to get each order once — but it cannot deduplicate children inside a bag.

Fix: make the collection a Set, whose elements are deduplicated by equals/hashCode (which must be the id-based implementation, or a transient element with a constant hash is fine but two loaded lines are distinguished by id); or add an @OrderColumn so the list is indexed; or fetch only one collection per query.

Prevention: one to-many fetch per query as a rule, and Sets for collections that have no natural order.

Land it A bag cannot say no to a duplicate — when a join multiplies rows, only a Set or an indexed list can put them back.

Likely follow-ups
"Hibernate 6 removed the need for distinct. What did the old distinct do, and why was it a problem?"

Before Hibernate 6, a join fetch of a collection returned the parent once per child row in the result list, so 20 orders with 50 lines each gave a list of 1,000 Order references, mostly repeats of the same instances.

The idiom was to add select distinct o, which made Hibernate deduplicate the parents in memory, but it also passed DISTINCT to SQL, forcing the database to sort or hash a thousand wide rows for no reason. The workaround was the hibernate.query.passDistinctThrough hint set to false.

Hibernate 6 deduplicates parents by identity always, so distinct is not needed and, if written, does go to SQL and does cost a sort. The children inside a bag are a different matter: they were never deduplicated and still are not.

"The collection must stay a List for ordering. What are your options?"

Two. Add @OrderColumn(name = "line_no"), which makes the list indexed: Hibernate stores the position in the column and uses it to place each row, so duplicates from a join land on the same index and collapse.

That changes the schema and makes Hibernate manage the column, including rewriting positions when a line is removed from the middle.

Or keep the bag and use @OrderBy("lineNo") for ordering, which only adds an ORDER BY to the load and does not fix duplication, and then enforce one collection fetch per query so the join never multiplies.

The second is cheaper and is what I would do, with a comment on the mapping and a test that fetches the order with a second collection and asserts the line count.

A Set with @OrderBy gives a LinkedHashSet with ordering and deduplication, which is often the best of both.

"How would you detect this class of bug before it reaches JSON?"

Three checks.

In the integration test for the endpoint, seed an order with a known number of lines and a second collection with more than one element, then assert the line count in the response equals the seeded count; that fails the moment a second to-many fetch is added.

In the persistence layer, a small test helper that runs every named query and entity graph and asserts that no query fetches more than one to-many path, by inspecting the JPQL or the EntityGraph attribute nodes.

And in review, a rule that a @Query with two join fetch keywords on collections needs a comment explaining why. The first is the important one because it tests the observable behaviour and costs nothing to write.

"Does the same duplication appear with an @EntityGraph that lists two collections?"

Yes, and it is easier to cause because the graph hides the SQL. An entity graph with two collection attribute nodes makes Hibernate generate a single SELECT with two left joins, which is the same Cartesian product as two join fetches.

If both are bags, Hibernate throws the same MultipleBagFetchException at query time. If one is a Set and one a bag, the bag duplicates silently, which is this scenario.

A graph is not a magic way around the join fetch rules; it is the same fetch plan written as annotations. The rule stays: one to-many per graph, and the second collection through @BatchSize or a subgraph-free second query.

Q86. "What is the difference between Hibernate.initialize(), a join fetch, and touching the collection? When does each belong?"

Reveal answer

Strong answer Touching the collection — order.getLines().size() — initialises it through a lazy load at that point, in the current session; it is the N+1 when done in a loop, and it is fine for one entity.

Hibernate.initialize(order.getLines()) does exactly the same load but says so explicitly, and it participates in batch fetching: called on one order, with @BatchSize it loads that order's lines and up to 49 other pending collections in one IN-list statement.

It exists to make a deliberate "load this before the session closes" visible in code, typically just before returning from a service method that must hand back an entity with a populated collection.

A join fetch loads the collection in the same statement as the parent, with no second round trip, and is the right choice when the query itself knows the children are needed.

So: join fetch when the query knows; initialize when the service decides late and wants the batching; touching when it is one object and you do not care about readers of the code knowing.

What none of them do is make the collection safe after the session closes for collections you did not initialise — a partially initialised graph is still a graph with live proxies at its edges.

Land it Fetch in the query when you can, initialise explicitly when you must, and never rely on an accidental getter to do the loading.

Likely follow-ups
"Is Hibernate.initialize the same as Hibernate.unproxy? When would you use each?"

They differ in what they return. Hibernate.initialize(obj) loads the proxy's state and returns nothing; the variable still holds the proxy, now initialised. Hibernate.unproxy(obj) initialises and returns the real underlying entity instance, unwrapped from the proxy class.

I use unproxy when code needs the concrete class, such as a cast to a subclass in an inheritance hierarchy or a switch over sealed types, because a proxy's class is the declared supertype and the cast would fail.

I use initialize when I only need the data present before the session closes and want the reference to stay stable. Both must run inside the session that owns the proxy; called on a detached proxy they throw the same LazyInitializationException.

"You said join fetch when the query knows. What if the query is a Spring Data derived method you did not write the JPQL for?"

Then the fetch plan is expressed with @EntityGraph(attributePaths = {"lines", "customer"}) on the derived method, which Spring Data passes to Hibernate as a fetch graph, or with a named graph declared on the entity and referenced by name.

Hibernate applies it as joins on the generated SQL, so the effect is the same as a join fetch.

The limits are the same too: no more than one collection path, and never on a method that takes a Pageable with a collection in the graph, which triggers in-memory pagination.

If the graph is getting complicated, I stop and write the JPQL, because a derived method with a five-attribute graph is a query pretending to be a method name.

"What does 'partially initialised graph with live proxies at its edges' cost you in practice?"

It costs a runtime failure at the first edge someone touches after the transaction. Say the service initialises order.getLines() and returns the order.

A caller who later calls line.getProduct().getName() hits an uninitialised proxy on product, and since the session is closed, gets a LazyInitializationException from a place that looks innocent. The failure is data-dependent and shows up in production on a code path that was not exercised in tests.

That is the argument for mapping the loaded data to a record DTO inside the transaction: the record has no edges, and if a field is missing it is missing at compile time. Returning entities with "enough" initialised is a contract enforced by nothing.

"How would you verify in production which of the three is actually happening on a given endpoint?"

Hibernate statistics separate them. getEntityFetchCount() and getCollectionFetchCount() count lazy loads that ran as their own statements; join fetches count as part of the query and do not increment those.

So an endpoint with a join fetch shows one query execution and zero collection fetches; the same endpoint with touch-in-loop shows one query and N collection fetches; with initialize plus batching it shows one query and N divided by 50 fetches.

I would read the deltas per request through the filter from Q110 and put collection fetches per request on the dashboard for the busiest endpoints. That number, more than total statement count, tells you which loading strategy is running.

Q87 · Scenario. "A team turned open-in-view off and 40 endpoints started throwing LazyInitializationException. The manager wants it back on. Make the case and the plan."

Reveal answer

Strong answer The case: each of those 40 exceptions marks a place where a query was running in the view layer, outside any transaction, un-batched and invisible — with OSIV on, those were 40 hidden N+1s and 40 places where a pool connection was re-borrowed while the response was being written.

The exceptions did not create a problem; they revealed one that was already costing latency and connections in production.

The plan, so the manager gets a schedule rather than a lecture: keep OSIV off in the test profile and on in production for two sprints; classify the 40 by the access pattern — most will be controllers returning entities to Jackson, a few mappers touching lazy fields; fix the controllers by returning DTOs built inside the service transaction (the biggest group, one pattern); fix the mappers with join fetch or an @EntityGraph on the query they use; add assertSelectCount tests to the ten busiest endpoints as you touch them; then flip production.

Measure before and after: statements per request and Hikari active-connection time. What I would not do: put @Transactional on the controllers as a shortcut, which is OSIV with extra rollback risk, or leave OSIV on and call it done.

Land it OSIV off converts hidden queries into visible exceptions — the plan is to fix them in priority order, not to hide them again.

Likely follow-ups
"Explain exactly what open-in-view does with the connection during response writing, because the manager will ask."

OpenEntityManagerInViewInterceptor opens an EntityManager before the controller runs and closes it after the view has rendered, so the persistence context lives for the whole request. Transactions still end in the service layer, and when a transaction commits, Hibernate returns the connection to the pool.

But when the serialiser then touches a lazy collection, Hibernate borrows a connection again from the pool, in autocommit mode, runs the lazy SELECT, and returns it. With a large response that can happen dozens of times, each borrow competing with real transactions for the pool.

Under load, response writing waits on getConnection, which is why OSIV shows up as pool exhaustion rather than as slow queries. That is the sentence for the manager: OSIV lets the JSON layer use the database pool.

"Two sprints in, 30 are fixed and 10 are hard. The manager wants to flip production now. Do you?"

Not blindly. I would quantify the ten: which endpoints, how much traffic, and what fails, since each one would go from a hidden query to a 500 error.

If they are low-traffic admin endpoints, I flip production and fix them behind an error budget, because the benefit on the busy endpoints is already earned.

If one of them is a hot path, I fix that one first even if it means a temporary @Transactional(readOnly = true) on the controller method for that endpoint alone, with a ticket and a date, which is OSIV scoped to one place.

What I do not accept is flipping production with a known hot endpoint that will throw, or keeping OSIV on for everyone because of ten stragglers. The setting is global, so the decision is about the worst remaining endpoint.

"Why is @Transactional on the controller worse than open-in-view rather than just equivalent?"

Because it adds rollback semantics to code that was not written for them. With OSIV the lazy loads after the service transaction run in autocommit, outside any transaction, so an exception while rendering does not touch the database.

With @Transactional on the controller, the whole request is one transaction: the service's commit becomes a participation in the outer transaction, not a real commit, so a serialisation error after the service returned rolls back the business change that the user believes succeeded.

The connection is also held for the entire request, including the response write, rather than re-borrowed briefly. And any exception thrown by the controller marks the transaction rollback-only, giving UnexpectedRollbackException in places that never expected transactions. It is OSIV with the failure modes of Q14 added.

"How would you find the 40 endpoints before turning OSIV off, rather than after?"

Turn it off in the test profile first and run the integration suite, which finds the ones with tests.

For the rest, run the application in staging with OSIV on but with Hibernate statistics and the datasource proxy enabled, and log a warning whenever a statement executes outside a Spring-managed transaction; a small QueryExecutionListener checks TransactionSynchronizationManager.isActualTransactionActive() per statement.

Replay a day of production traffic or run the smoke tests, and the warning log lists every endpoint that lazy-loads in the view, with the entity and collection name from the SQL. That list is the plan, ranked by request count.

It is a day of work and it turns the two-sprint estimate from a guess into a count.

Q88. "Subselect fetching (@Fetch(FetchMode.SUBSELECT)) — how does it differ from batch fetching, and when is it the better choice?"

Reveal answer

Strong answer Subselect fetching loads the collection for every parent returned by the original query in one statement, by re-running the original query's WHERE clause as a subquery: select ... from order_line where order_id in (select o.id from orders o where o.status = ?).

It fires on the first touch of any of those collections. Batch fetching, by contrast, loads collections for up to N parents that happen to be in the persistence context, using an IN list of ids.

The differences: subselect is always exactly two statements regardless of the number of parents, whereas batch fetching is one plus N/50; subselect re-executes the parent query's predicate, which the database may plan well (it can use the same index) or badly if the predicate is expensive; and subselect only works for collections whose parents came from one query — parents loaded by find() individually do not share a query to re-run.

It is the better choice when a query returns thousands of parents and the loop will touch every collection, so N/50 statements would still be many; batch fetching is better when only some collections will be touched, or parents come from multiple queries.

Both compose with pagination, which join fetch does not — subselect specifically re-applies the LIMIT in the subquery in Hibernate 6.

Land it Subselect is "two statements, always"; batch is "one per fifty touched" — pick by how many parents and how many collections you will actually read.

Likely follow-ups
"What happens with subselect fetching if the original query used setMaxResults and the underlying data changed between the two statements?"

The subselect re-executes the parent query's predicate with its limit inside the IN subquery, but it is a separate statement, so it sees the database as it is at that moment.

Under READ COMMITTED, if a new order matching the predicate was committed between the two statements and sorts into the first page, the subquery's page shifts by one: the collection load includes lines for an order that was not in the first result and omits lines for the last order of the original page.

That order's collection then stays uninitialised and gets loaded individually on touch, so correctness holds, but the statement count is three rather than two. Under REPEATABLE READ both statements share a snapshot and the problem disappears.

It is a reason to prefer batch fetching, which uses the ids actually loaded, when pages are involved.

"Can subselect and batch be combined on the same collection?"

They are alternatives on one collection, not layers.

@Fetch(FetchMode.SUBSELECT) and @BatchSize can both be declared, and Hibernate uses subselect when the parents came from one query it can re-run, and falls back to batch loading when they did not, for example parents loaded by find() or from several queries.

So the combination is a reasonable default for a collection that is read in both shapes.

What they cannot do is split one load: a subselect fetch always loads the collections for every parent of the original query, even if the loop stops after ten, so on a query returning 10,000 parents where only the first 10 are touched, subselect is a bad choice and batch would have loaded 10.

"The subselect version is slower than the batch version in production. Why might that be?"

Because the subselect re-runs the parent query's predicate, and that predicate can be far more expensive than a primary-key IN list.

If the parent query was a search with a text match, a join, or a non-selective filter that took 800 milliseconds, the collection load pays that again inside the subquery, whereas a batch load probes the child table by 50 ids on an index in a millisecond.

Confirm with EXPLAIN ANALYZE on the generated child statement; if the plan shows the parent's expensive scan inside the subquery, that is the cause.

The fix is to switch that collection to batch fetching, or to make the parent query cheap with an index, which helps both statements. Subselect shines when the parent predicate is a cheap indexed range and the parent count is large.

"How does the database plan a where order_id in (select id from orders where ...) versus an IN list of literals?"

Differently, and it matters. With an IN list of bound ids, the planner knows the count and can choose an index probe per value, a nested loop over 50 lookups, which is near-constant time.

With an IN subquery, the planner treats it as a semi-join: it may run the subquery first, hash its result, and hash-join against order_line, or it may push the join into a nested loop if it estimates few parents.

The estimate is the risk; a bad row estimate on the parent predicate turns the semi-join into a sequential scan of order_line. On PostgreSQL 15 and later the estimates are decent, but I still check the plan for the hot collections.

The IN list's plan is boring and predictable, which in production is a virtue.

Q89 · Scenario. "A Kafka consumer processes one message per transaction, and each message loads an order plus its lines and customer. Under a backlog of 2 million messages it runs at 400 per second. What would you try first?"

Reveal answer

Strong answer Symptom: throughput bounded by per-message database round trips.

Evidence: statements per message — likely one order SELECT, one lines SELECT, one customer SELECT (EAGER or touched), one UPDATE, one COMMIT — five round trips at about 0.5 milliseconds each is 2.5 milliseconds, which caps a single thread near 400 per second.

First try: reduce statements per message — a single join fetch query for order, lines and customer turns three selects into one, so five round trips become three.

Second: batch the messages — poll 100 records, load all 100 orders in one query with where o.id in :ids and their lines by batch fetch, process them, and commit once; that is roughly five round trips per 100 messages instead of per message, a 20-fold gain, with the Kafka offset committed after the database transaction.

Third: parallelism — more partitions and consumer threads, since each thread's throughput is latency-bound, not CPU-bound. Also enable JDBC batching for the UPDATEs so 100 versioned updates go in two batches.

What I would not do first: add a second-level cache, because orders are write-heavy and every message invalidates what the previous one cached. Prevention: a per-message statement-count metric as a dashboard line.

Land it Throughput is round trips per message — cut them with one fetch query, then amortise them across a batch of messages.

Likely follow-ups
"You batched 100 messages per transaction and now one bad message rolls back the other 99. How do you handle it?"

That is the real cost of batching, and it needs a designed answer rather than a retry loop.

The consumer catches the failure for the batch, then falls back to processing that batch one message per transaction, so the 99 good ones commit and the one bad one is isolated.

The bad one goes to a dead-letter topic with the exception and the offset, and the consumer commits past it. In Spring Kafka this is the DefaultErrorHandler with a DeadLetterPublishingRecoverer on a batch listener, which already implements the fall-back-to-singles behaviour.

The important property is idempotency: because the batch was rolled back and re-processed, every message may be applied twice, so the handler must use the order's version or an idempotency key. Batching without idempotent handlers is a lost-write generator.

"Where exactly does the 0.5 milliseconds per round trip come from, and what if the database is in another availability zone?"

It is the network latency between the application and the database plus the driver's parse and the database's execute for a trivial statement. Same-zone in a cloud region it is typically 0.3 to 0.8 milliseconds; cross-zone it is 1 to 2 milliseconds; cross-region it is tens.

So the same five statements per message cap a thread at 400 per second same-zone, around 150 cross-zone, and a few tens cross-region.

The arithmetic is why round trips matter more than CPU for this workload, and why moving the consumer to the database's zone can double throughput before any code changes.

I would measure the actual number with a SELECT 1 loop from inside the pod, and put it in the capacity model, because every plan for this job is a multiple of that number.

"The join fetch worked, but throughput only went from 400 to 550. Why not 650?"

Because not every round trip is the same length, and because some work is not round trips.

The three SELECTs I collapsed were cheap primary-key probes; the UPDATE and the COMMIT are heavier, since the commit waits for the WAL flush to disk and, with synchronous replication, for the standby's acknowledgement, which can be two milliseconds on its own.

So removing two cheap statements saves less than two-fifths of the time.

I would measure the per-statement time from the session metrics log to see where the remaining time is; if it is commit, the batch-of-100 design amortises exactly that cost, which is why it is the second step.

If it is the Kafka poll or the JSON deserialisation, the bottleneck has left the database and a profiler is the next tool.

"When would you reach for the second-level cache here after all?"

For the customer reference, if customers change rarely and the messages for one customer arrive in bursts. A READ_ONLY or NONSTRICT_READ_WRITE region on Customer would serve the to-one lookup from memory and remove one probe per message without a join.

It would not help for the order, which is written on every message and therefore invalidated on every message. The test is the hit rate: if a customer appears in fewer than three consecutive messages the cache does not pay.

In practice, the join fetch already removes the customer SELECT, so the cache buys nothing here; I mention it because the interviewer wants to hear that the decision is driven by the write frequency of the cached type, not by whether a cache is available.

Q90. "What is bytecode enhancement in Hibernate, what does it enable for lazy loading, and why do most Spring teams not use it?"

Reveal answer

Strong answer Enhancement rewrites entity class files at build time (through the Hibernate Gradle or Maven plugin) or at load time to add interception to field access. It enables three things.

Lazy loading of individual basic attributes — a large @Lob or JSON column marked @Basic(fetch = LAZY) is skipped by the SELECT and loaded on first access, which without enhancement is silently ignored and always loaded.

Lazy to-one on the inverse side of a one-to-one (Q52) without a proxy, because the enhanced getter can query on demand and return null honestly.

And inline dirty tracking: enhanced setters record which fields changed, so flush compares a bitmask instead of walking every field against the snapshot.

Most Spring teams skip it because it is a build step that changes class files, complicates debugging and IDE hot-reload, interacts badly with some Lombok and Kotlin setups, and the gains are marginal for typical entity sizes — the snapshot comparison is fast, and lazy basic attributes are better handled by moving the big column into a separate @OneToOne entity.

It matters at the margins: very wide entities, huge persistence contexts, or a hard requirement to lazy-load a blob in place.

Land it Enhancement buys lazy basics and cheaper dirty checks at the cost of a build-time rewrite — worth it for wide rows, not for a normal domain model.

Likely follow-ups
"How would you enable enhancement in a Gradle build, and what do you check afterwards?"

Apply the org.hibernate.orm Gradle plugin and configure hibernate { enhancement { enableLazyInitialization = true; enableDirtyTracking = true; enableAssociationManagement = false } }; the Maven equivalent is hibernate-enhance-maven-plugin with the same flags. Afterwards, I check three things.

The compiled entity class implements org.hibernate.engine.spi.ManagedEntity and PersistentAttributeInterceptable, visible with javap. A test that loads an entity with a @Basic(fetch = LAZY) column asserts, through the SQL log, that the column is absent from the SELECT and a second statement appears on first access.

And the IDE runs tests against enhanced classes, because a test run from the IDE with unenhanced classes silently behaves differently from the build. That last one is the source of most "works in CI, not locally" confusion with enhancement.

"What does association management do, and why did you say leave it off?"

Association management makes the enhanced setter on one side of a bidirectional relationship update the other side automatically, so line.setOrder(order) also adds the line to order.getLines().

It sounds convenient, but it hides collection initialisation: setting the parent on a line now touches the parent's lazy collection to add to it, which loads it, which is an N+1 inside a setter that looks like a field assignment.

It also changes behaviour between enhanced and unenhanced classes, so unit tests without enhancement pass and integration tests fail. The explicit addLine helper on the aggregate that sets both sides is two lines of code, visible, and the same everywhere.

I turn on lazy initialisation and dirty tracking only, and only when a measurement says the entity is wide enough to need them.

"Can enhancement change the result of a dirty check compared with snapshot comparison?"

Yes, in one direction. Snapshot comparison sees the state; enhancement sees the calls.

If code mutates an object inside an entity field without going through a setter, for example order.getMetadata().put("k", "v") on a JSON-mapped map, the snapshot compare notices the map changed at flush, whereas the inline dirty tracker never saw a setter and does not mark the field dirty, so the change is lost.

Hibernate handles the common case for its own collections, but not for arbitrary mutable value types. The other direction, a setter called with the same value, is handled by both.

The verification is a test that mutates such a nested value and asserts an UPDATE was issued. This is the mechanism behind the "enhancement lost my change" bug reports, and it is why I say the gain is marginal for normal models.

"You mentioned moving a large @Lob into a separate @OneToOne entity. What does that mapping look like and what is its own trap?"

The document row becomes DocumentContent with @Id shared through @MapsId from the owning Document, and Document holds @OneToOne(fetch = LAZY) @MapsId or, simpler, keeps only the id and loads content through its own repository method when needed.

The blob never appears in the document SELECT, no enhancement required. The trap is the inverse-side one-to-one from Q82: if Document maps the association with mappedBy, Hibernate cannot proxy it and eagerly loads the content on every document load, which defeats the split.

So the association is mapped from the content side, or with @MapsId on the content side and optional set to false so the proxy is honest. I usually skip the association entirely and let a service load content by id.

Q91 · Design. "Design the fetch strategy for an order detail page (one order, its lines, each line's product name, the customer) and an orders list page (50 orders with line counts) so that neither issues more than two statements."

Reveal answer

Strong answer Requirements: bounded statement count per page, no entity serialisation across the transaction boundary, and mappings left LAZY so other paths are not taxed.

Detail page: one JPQL query, select o from Order o join fetch o.customer join fetch o.lines l join fetch l.product where o.id = :id — one to-one fetch and one collection fetch in the same statement is fine; the product join fetch is a to-one hanging off the collection and does not multiply rows.

Map the result to an OrderDetailDto record inside the transaction. One statement. If lines could be hundreds, switch l.product to @BatchSize and accept a second statement instead of a wide join.

List page: never load entities — a projection query select new OrderRowDto(o.id, o.status, o.total.amount, c.displayName, size(o.lines)) from Order o join o.customer c where ... order by o.createdAt desc with setMaxResults(50) and keyset pagination on (createdAt, id); size() compiles to a correlated count subquery, and there is no collection fetch so pagination is honest.

One statement, plus an optional count query if the UI insists on total pages — prefer a Slice and skip it.

Trade-offs: the detail query is one wide statement, which is right for one order; the list query is narrow and cannot lazily navigate anywhere, which is the point.

What I would not do: an @EntityGraph on the list repository method with Pageable, which triggers in-memory pagination the moment the graph includes lines.

Land it Fetch the graph for the one-object page, project for the list page, and let the statement count be the acceptance test.

Likely follow-ups
"The requirement changes: the list page now needs each order's first three line descriptions. What changes?"

The projection can no longer express it in one row, because three lines per order is a to-many result. Two honest options.

Keep the list query at one statement for the order rows, then a second statement select l.order.id, l.description from OrderLine l where l.order.id in :ids and l.lineNo <= 3 order by l.order.id, l.lineNo for the fifty ids, grouped in Java into the DTO; two statements, still within budget, and the second one is an indexed probe.

Or a lateral join in native SQL on PostgreSQL that returns the three descriptions as an array per row, which stays at one statement but ties the query to the engine. I would pick the two-statement version unless the endpoint is the hottest in the system.

What I would not do is load entities with lines to take three, which pulls every line of fifty orders.

"You are out of time and can ship only one of the two pages properly. Which do you cut, and how?"

I ship the list page properly, because it runs fifty rows per request under paging and is the one that becomes the in-memory pagination incident or the N+1 at scale.

The detail page loads one order, so a worse fetch plan there costs a handful of statements per request, not hundreds.

The cut for the detail page: use findById with @BatchSize on the collections and map to the DTO inside the transaction, accepting three or four statements instead of one, with an assertSelectCount upper bound of five and a ticket to replace it with the single fetch query.

That keeps the transaction boundary and the DTO contract, so the later optimisation changes one query and nothing else.

"Why does the product join fetch off the collection not multiply rows, but a second collection would?"

Because of cardinality. A line has exactly one product, so joining product onto the line rows adds columns to each row without adding rows; 50 lines stay 50 rows.

A second collection, say payments, has many rows per order, and joining it onto rows that are already per-line multiplies: 50 lines times 3 payments is 150 rows, each combination once. To-one joins are free in row count and only cost width; to-many joins multiply.

That is the rule I apply when reading a fetch plan: count the to-many paths, and if there is more than one on the same parent, expect a product.

It also explains why the list page's size(o.lines) is safe: it is a correlated count, not a join, so it produces one number per row.

"How would you verify the 'no more than two statements' requirement stays true after other developers touch these pages?"

With a statement-count assertion in each page's integration test, using the datasource proxy: assertSelectCount(1) for the detail page and assertSelectCount(1) or 2 for the list, seeded with enough orders and lines that an N+1 would be visible. Those tests run on every pull request.

In production, the per-endpoint statements-per-request metric from the statistics filter has an alert at three.

Between them, a regression fails the build before merge and, if one slips through with a data shape the test did not cover, pages someone within minutes rather than at the next capacity review. The requirement lives in a test, not in a document.

Q92. "What does a LazyInitializationException actually mean at the level of the proxy, and why does 'just add @Transactional' sometimes make it worse?"

Reveal answer

Strong answer A proxy or persistent collection carries a reference to the session that created it. On first access it asks that session to run the load.

If the session is closed, the reference is dead, and Hibernate throws LazyInitializationException with "no Session" — or "could not initialize proxy" if the session exists but is not open.

It means exactly: this object's data was never loaded and the unit of work that could have loaded it is over.

Adding @Transactional to the code that touches the field opens a new session, but the proxy still points at the old, closed one — the exception persists, unless the new transaction reloads the entity.

Where it "works", it is because the annotation was placed around the original load as well, extending that session to cover the access.

That is the sense in which it makes things worse: the fix stretches the transaction to cover more code — often a whole controller or a loop with remote calls — so the persistence context lives longer, holds more, and the connection is pinned across non-database work (Q18).

The proper fixes load what is needed inside the existing unit of work and hand out data, not proxies.

Hibernate's hibernate.enable_lazy_load_no_trans exists to paper over it by opening a temporary session per lazy load; it is an anti-pattern because each such load is its own connection and its own unbatched query.

Land it The proxy remembers a dead session; widening the transaction keeps the session alive longer, which is the cost you were trying to avoid.

Likely follow-ups
"What is the mechanism behind hibernate.enable_lazy_load_no_trans, and why do you call it an anti-pattern rather than a convenience?"

With that property set, a proxy or collection whose session is closed opens a temporary session on the fly, borrows a connection from the pool, runs the load, and closes the session again.

Each lazy access is its own session, its own connection checkout, and its own autocommit statement, with no batching because no other proxies share the temporary session. A loop over a hundred detached orders touching lines becomes a hundred connection borrows.

It also breaks consistency: the loaded data comes from a different snapshot than the parent, so an order and its lines can be from different moments. And it hides every one of these costs behind a property nobody remembers is on.

It is OSIV without a request boundary, which is why I would remove it from any configuration I inherit and fix the exceptions properly.

"Is there a legitimate way to re-attach a detached entity so its proxies work again?"

Not the proxies themselves. em.merge(detached) returns a new managed copy whose lazy fields are fresh, uninitialised proxies bound to the new session, but the original detached object and its old proxies stay dead; code must use the returned instance.

Hibernate's native session.lock(entity, LockMode.NONE) or the removed update() re-associated the same instance, and its proxies were rebound to the new session, but that path is gone from Hibernate 7 for good reasons and Spring Data never exposed it.

The practical answer is to reload by id in the new transaction and fetch what is needed. If the goal is to carry state across requests, carry a DTO or the id, not a managed graph, which is the Q119 and Q126 lesson as well.

"How do you tell from the exception message which of the two states you are in?"

The message names the proxy and the reason. "could not initialize proxy [com.x.Customer#42] - no Session" means the proxy's session reference is null or closed: the transaction ended and the object was used after it.

"could not initialize proxy - the owning Session was closed" is the same state phrased by an older version.

The rarer "could not initialize proxy - the owning Session is disconnected" means the session exists but its connection was released, which happens with a connection-release mode that returns the connection after each statement and a lazy load attempted outside a transaction.

The first tells you to look at where the transaction ended; the last tells you to look at connection handling. The stack trace's first application frame is the access, and the fix goes into the transaction that loaded the object.

"A colleague argues that in a short controller with one service call, widening the transaction is harmless. When are they right?"

They are right when the controller does nothing but call the service and serialise, and the serialisation touches lazy fields that the service could have loaded anyway.

In that narrow case the transaction is the same length either way, and the difference is only where the boundary is drawn.

They are wrong the moment the controller does anything else: an authorisation call to another service, a second repository call, or a slow client writing the response, because the connection is now held for that time too.

And the boundary drifts, since the next developer sees a transactional controller and adds a remote call inside it.

I would accept the argument for one endpoint with a comment and a test, and still ask why the service does not return a DTO, which makes the question disappear.

Drill · Pagination, projections & DTOs

This group tests whether you know what a page really costs, and when to stop loading entities at all.

Q93 · Scenario. "A paginated endpoint with an @EntityGraph including a collection is fast on page one in dev and takes 40 seconds in production. The log shows HHH90003004. Explain and fix."

Reveal answer

Strong answer Symptom: page time proportional to table size, not page size.

Evidence: the warning "firstResult/maxResults specified with collection fetch; applying in memory" and a SQL statement with no LIMIT. Cause: the collection fetch multiplies rows, so a SQL LIMIT would cut an order's lines in half; Hibernate refuses to hand back a partial collection, so it fetches every matching row and paginates the Java list.

Dev has 300 orders and never notices; production has 4 million.

Fix, ranked: one, paginate the parent without the collection fetch — a query for the page of orders, then let @BatchSize load lines for those 20 in one IN-list statement, or run a second query join fetch o.lines where o in :page; two, for a read-only list, a projection with size(o.lines) that never fetches the collection; three, if the graph must stay, a two-step id page — select 20 ids with LIMIT, then fetch the graph for those ids.

Set hibernate.query.fail_on_pagination_over_collection_fetch: true so this shape throws in tests. Prevention: a rule that Pageable methods never carry an entity graph with a to-many path, and a production-sized dataset in staging.

Land it A page of parents plus a batch of children is two cheap statements; a page over a collection join is the whole table in memory.

Likely follow-ups
"You applied the batch-size fix and page one is fast, but page 200 is still slow. Why?"

Because the fix removed the in-memory pagination and left the offset pagination in place.

Page 200 with 20 rows per page is OFFSET 3980, which is fine, but the customer is on a filtered list where the database must produce and discard every earlier matching row, and with a sort on a non-indexed column it sorts the whole matching set first.

Check the plan with EXPLAIN ANALYZE: a sort node over a large row estimate confirms it. The fix is an index that matches the sort and filter so the offset walks the index, or keyset pagination through ScrollPosition.keyset() so every page seeks directly.

The Page count query is the other suspect, since it scans the same filtered set per request; switching to Slice removes it.

"What does the two-step id page look like in code, and what is its trap?"

First statement: select o.id from Order o where ... order by o.createdAt desc, o.id desc with setFirstResult and setMaxResults(20), a narrow query with a real LIMIT. Second statement: select o from Order o join fetch o.lines where o.id in :ids order by o.createdAt desc, o.id desc, which joins only the 20 parents.

The trap is ordering: the second query must repeat the ORDER BY, because an IN list returns rows in index order and the fetched orders would come back shuffled.

The other trap is that the second query cannot fetch two collections either, so the rule of one to-many per query still applies. Spring Data does not do this for you, so it lives in a custom repository fragment with a comment saying why.

"Why does Hibernate paginate in memory instead of throwing by default?"

Historical compatibility. Hibernate has applied pagination in memory for collection fetches since version 3, and thousands of applications depend on it working on small datasets, so making it an error by default would break them on upgrade.

Hibernate 5.2.13 added the warning HHH90003004 and later the hibernate.query.fail_on_pagination_over_collection_fetch property, false by default, so teams can opt into the failure. As of Aug 2026, Hibernate 7 keeps the same default.

My position is that the property should be true in every profile: in tests so the shape cannot be written, and in production so a query that slipped through fails fast with a clear message instead of loading four million rows on a Monday morning. A fast failure is cheaper than a slow success.

"How would you have caught this in CI, given dev had 300 orders?"

Three ways, cheapest first. The property above set to true in the test profile makes the query throw regardless of data size, so the integration test for the endpoint fails on the shape alone.

Second, log scanning: fail the test run if the Hibernate log contains HHH90003004, which is a one-line JUnit extension.

Third, a datasource proxy assertion that the generated SQL for a paged endpoint contains limit or fetch first, which catches the same class without depending on Hibernate's warning code.

None of them need production-sized data, which is the point: the mistake is structural, and structural mistakes should be caught by structure, not by volume.

Q94. "Page versus Slice in Spring Data — what extra SQL does Page cost, and when is that count query surprisingly expensive?"

Reveal answer

Strong answer A Page runs two statements: the page query with LIMIT and OFFSET, and a select count(...) with the same WHERE clause to compute total elements and total pages.

A Slice runs one statement, asking for one row more than the page size to learn whether a next page exists, and reports no total. The count is surprisingly expensive in three cases.

On a large table with a non-selective filter — "all orders in the last year" — the count scans or counts millions of index entries every time a user opens the list, and on PostgreSQL count(*) cannot be answered from the index alone without visibility checks, so it visits heap pages too.

With a join fetch or an entity graph in the derived query, Spring Data must rewrite the count query without the fetch, and the generated count over a join can be wrong or slow.

With Specifications, the count query repeats the full predicate tree, which for a search screen with ten optional filters is the same heavy query twice.

Choose Slice for infinite-scroll and "next" navigation; choose Page only when the UI genuinely shows total pages, and then consider an approximate count from statistics or a cached count for the unfiltered case.

Land it Page is two queries, one of them a count that scales with the table — use Slice unless the number of pages is on screen.

Likely follow-ups
"The product owner insists on total pages. How do you serve it without the count on every request?"

Three patterns, by how exact the number must be.

For an unfiltered list, cache the count for a minute in Caffeine keyed by the filter hash, or maintain it in a counter table updated by the write path; a total that is a minute stale is fine for "page 3 of 412".

For a filtered search, use PostgreSQL's planner estimate: EXPLAIN (FORMAT JSON) of the count query returns the estimated rows in microseconds, and the UI shows "about 4,000 results". For an exact number under a threshold, run select count(*) from (... limit 10001) so the count stops at ten thousand and the UI shows "10,000+".

In Spring Data, pass a custom count query with @Query(countQuery = ...) or build the page with PageableExecutionUtils.getPage and a supplier that uses one of these. The exact count over millions on every keystroke is the one thing I refuse.

"When exactly does Spring Data skip the count query even for a Page?"

PageableExecutionUtils.getPage skips it when the answer is already known from the content: if the request is for the first page and the content is smaller than the page size, the total is the content size; and if it is a later page and the content is smaller than the page size, the total is offset plus content size.

So a small filtered result never pays the count. It cannot skip when the content fills the page, because then there may be more.

That is why a list where most searches return fewer than the page size is cheap even as a Page, and a list where users browse full pages pays the count every time.

Knowing that rule tells you which endpoints actually benefit from the switch to Slice.

"Why can the generated count query be wrong with a join fetch?"

Spring Data derives the count query from the JPQL by replacing the select clause with count(o) and removing fetch joins, because a fetch join in a count is invalid JPQL. If the original query also had a distinct or a to-many join that was not a fetch, the count runs over the multiplied rows and reports the number of joined rows rather than the number of parents, so a page of 20 orders reports 600 total elements. The fix is an explicit countQuery on the @Query annotation that counts distinct parent ids with the same WHERE clause. I check every Page-returning method with a join by reading the generated count SQL once in the log; it takes a minute and prevents a wrong total that no test with one parent would catch.

"On PostgreSQL, why is count(*) not answerable from the index alone?"

Because of multi-version concurrency. Every row version carries transaction ids that say which transactions can see it, and that visibility information lives in the heap page, not in the index entry.

An index-only scan is possible only for heap pages marked all-visible in the visibility map, which happens after vacuum has confirmed no old versions remain.

On a table with steady updates, many pages are not all-visible, so the count must visit the heap to check each entry, which is why count(*) on a busy table is a real scan.

MySQL InnoDB has a similar cost for a different reason: it also must check versions per row for the transaction's read view. Neither engine keeps a running row count per table, which is why the count query is the surprisingly expensive one.

Q95. "Offset pagination versus keyset pagination through JPA — how do you implement keyset, and what do you give up?"

Reveal answer

Strong answer Offset pagination — LIMIT 20 OFFSET 40000 — makes the database produce and discard 40,000 rows to return 20, so page 2,000 is 2,000 times slower than page 1, and rows inserted between requests shift the pages so users see duplicates or gaps.

Keyset pagination remembers the sort key of the last row on the page and asks for rows after it: where (o.createdAt, o.id) < (:lastCreatedAt, :lastId) order by o.createdAt desc, o.id desc with setMaxResults(20), which uses the index on (created_at, id) to start exactly where the last page ended, at constant cost for any page.

In JPA you implement it with a @Query and the row-value comparison (PostgreSQL supports the tuple syntax; on MySQL write it out as a < :x or (a = :x and b < :y)), or with Spring Data's ScrollPosition.keyset() and Window<T> API, available since Spring Data 3.1, which generates the predicate from the Sort.

You give up jumping to an arbitrary page number and total counts — keyset is "next" and "previous" only — and the sort must be over a unique combination (hence the id tiebreaker) or rows are skipped.

For a feed, an audit log, or an export, keyset is the only pagination that scales; for a small admin table with page numbers, offset is fine.

Land it Keyset makes every page cost the same by seeking on the sort key — the price is no page numbers, which most screens never needed.

Likely follow-ups
"Show me the Spring Data keyset call and what SQL it produces."

The repository method is Window<OrderRow> findByStatus(Status status, ScrollPosition position, Limit limit, Sort sort) or the equivalent through the fluent findBy(spec, q -> q.sortBy(sort).limit(20).scroll(position)). The first call passes ScrollPosition.keyset(), and each next call passes window.positionAt(window.size() - 1). With Sort.by(desc("createdAt"), desc("id")), Spring Data generates where status = ? and (created_at < ? or (created_at = ? and id < ?)) order by created_at desc, id desc fetch first 21 rows only, asking for one extra row to know whether a next window exists.

It expands the tuple comparison into the OR form, which is portable but plans slightly worse than a row-value comparison on PostgreSQL; on a composite index it still seeks. Available since Spring Data 3.1, stable in Spring Data 4 as of Aug 2026.

"What happens if the sort key is not unique and you forget the id tiebreaker?"

Rows are skipped or repeated at page boundaries.

If ten orders share the same created_at and the page ends in the middle of them, the next request asks for rows strictly after that timestamp and skips the remaining orders with the same value; with a non-strict comparison it repeats the ones already shown.

The bug is data-dependent, so a test with distinct timestamps never sees it. The rule is that the full sort key must identify a row uniquely, and the cheapest way to guarantee it is always appending the primary key as the last sort column.

I would enforce it in the code that builds the Sort, adding id automatically, and write a test with duplicate timestamps that walks every page and asserts each id appears exactly once.

"Can you offer both: keyset for next and previous, and a jump to page N for the first hundred pages?"

Yes, and it is a sensible hybrid. Offset is fine for small offsets, since OFFSET 2000 costs the database two thousand index entries, which is nothing.

So the API accepts either a page number up to a cap, say 100, served by offset, or a cursor, served by keyset, and the UI shows numbered links for the first pages and next-previous beyond.

The response always includes the cursor so the client can switch. What the hybrid must not do is allow an unbounded page number, because page 50,000 is the slow query.

Spring Data supports ScrollPosition.offset() and ScrollPosition.keyset() through the same Window API, so one repository method serves both.

"How do you make the cursor safe to hand to a client?"

The cursor encodes the last row's sort values, for example the timestamp and id, so it must be opaque, tamper-evident, and tied to the sort it was created for.

I serialise the values plus the sort specification to JSON, base64url-encode it, and append an HMAC with a server key so a modified cursor is rejected.

Without the HMAC a client can craft a cursor that changes the sort direction or points to another tenant's rows, which combined with a tenant filter mistake becomes a leak.

The cursor is also versioned so that a change in sort columns invalidates old cursors cleanly with a 400 rather than a wrong page. Spring Data's KeysetScrollPosition exposes the key map; the encoding and signing layer is application code.

Q96. "Interface projections, class (record) projections, and Tuple — what SQL and what object costs do they have, and which do you default to?"

Reveal answer

Strong answer A class projection — select new com.x.OrderRow(o.id, o.status) in JPQL, or a record named as the return type of a derived Spring Data method — selects exactly those columns and calls the constructor per row: the leanest option, no proxies, no persistence context involvement, and the result is a plain immutable value.

A closed interface projection (getters that match entity properties) is also a column-limited SELECT; Spring Data creates a JDK proxy per row that reads from a map, which costs a little allocation and reflection per row but is fine at page sizes.

An open interface projection using @Value("#{target.first + ' ' + target.last}") forces Spring Data to load the whole entity and evaluate the expression in Java — a hidden full-row select that surprises people.

Tuple results are untyped column bags, useful for ad-hoc native queries and nothing else. Nested projections that reference a to-many association load the entities behind the scenes.

Default to records for anything that leaves the service layer, because they double as the API shape and are visible to the compiler; use interface projections when the same query serves several column subsets through a dynamic Class<T> parameter.

Land it Records are the honest projection — exact columns, no proxy — and any projection that mentions a collection or a SpEL expression has quietly become an entity load.

Likely follow-ups
"How does Spring Data know to select only the projection's columns for a record return type?"

For derived queries and for @Query with a JPQL select of an entity alias, Spring Data inspects the return type.

For a record or class projection it builds a criteria query with a constructor expression over the properties matching the constructor parameter names, which requires the parameter names to be present in the class file, true for records always and for classes when compiled with -parameters.

For an interface projection it selects the properties named by the getters into a Tuple and wraps each row in a proxy. If the @Query already has its own select list, Spring Data uses it as written and maps positionally or by alias.

Verification is one look at the SQL log: a projection that selects every column of the table has fallen back to an entity load, and the usual cause is a SpEL @Value or a nested property path.

"What if the projection needs a computed value, like a line count, without falling into the open-projection trap?"

Compute it in the query, not in the projection. In JPQL, select new OrderRow(o.id, o.status, size(o.lines)) from Order o compiles the count into a correlated subquery, and the record receives a Long.

For a derived method with an interface projection, the same is not expressible, so switch to @Query.

If the computation is a Java expression over columns, say a display name from first and last, either concatenate in JPQL with concat or give the record a derived accessor method that computes it from the two stored components, which costs nothing per row.

The open projection with @Value("#{target.first + target.last}") is the one form that quietly loads the entity, so it is the one I forbid in review.

"Why do you say a nested projection over a to-many loads entities behind the scenes?"

Because a projection is a flat row, and a collection is not. When an interface projection declares List<LineSummary> getLines(), Spring Data cannot express that as columns, so it loads the Order entity, then walks getLines(), which triggers the lazy collection load, then projects each line.

The SQL log shows the full entity select and an N+1 on lines, which is worse than the entity query you were replacing. For nested to-one properties, such as getCustomer().getName(), recent Spring Data versions do select the joined column, but historically that too loaded the parent.

The safe pattern for a list with children is two flat projections, one per level, joined in Java by parent id, or the JSON aggregation approach on the database side.

"Does the record projection interact with the persistence context at all, and what does that mean for flushing?"

The result objects do not: records are not entities, so nothing is registered in the persistence context, no snapshots are taken, and the memory per row is the record itself.

The query execution does, in one way: with AUTO flush mode, Hibernate flushes pending changes to the tables the query reads before running it, so a projection query after modifying orders still triggers the UPDATE first.

In a read-only transaction there is nothing to flush and the flush is skipped entirely.

That combination, read-only transaction plus record projection, is the leanest read path available through JPA: one statement, no context growth, no dirty check, and the result is safe to return across the boundary because it holds no proxies.

Q97 · Design. "Design a search endpoint over orders with eight optional filters, sorting on four columns, and 10 million rows, using Spring Data JPA, without falling into the Specification traps."

Reveal answer

Strong answer Requirements: any combination of filters, predictable latency, no in-memory pagination, no count on every request, and query shapes that the database can plan.

Design: a JpaSpecificationExecutor with one small Specification<Order> per filter, composed with Specification.allOf(...) only for filters that are present, so the WHERE clause contains exactly the active predicates.

Return a projection, not entities: Spring Data's Specification API returns entities, so either use the findBy(Specification, Function<FluentQuery>) fluent API with .as(OrderRow.class) to project, or build the equivalent with the criteria API's CriteriaBuilder.construct.

Pagination by keyset through ScrollPosition.keyset() with a fixed tiebreaker on id; return a Window, not a Page, so no count runs.

Sorting restricted to an allow-list of four indexed columns, each with a composite index that leads with the most selective common filter (customer_id, status) — E8 covers the leading-column rule. Cap page size at 100.

Traps avoided: joins inside Specifications create duplicate rows when the join is to-many, so filters on lines use exists subqueries; distinct with sorting on a joined column fails on PostgreSQL; and the count query doubles the load.

Trade-offs: eight filters times four sorts is many query shapes, so plan cache pressure is real; keeping predicates parameterised (never string-built) limits it. What I would not do: full-text search or faceted counts through this path — that belongs in a search index.

Land it Compose only the active predicates, project instead of loading, keyset instead of count, and index for the sorts you allow.

Likely follow-ups
"The requirement changes: two of the filters are on line-item fields, like SKU. How does that change the Specification?"

A filter on a child collection must not join the collection in the main query, because a join to lines multiplies the order rows and either duplicates results or forces a distinct that breaks sorting on PostgreSQL. The Specification builds an exists subquery instead: Subquery<Long> sq = query.subquery(Long.class); Root<OrderLine> l = sq.from(OrderLine.class); sq.select(l.get("id")).where(cb.equal(l.get("order"), root), cb.equal(l.get("sku"), sku)); return cb.exists(sq);.

The database plans it as a semi-join, one row per order regardless of matching lines, and an index on (sku, order_id) makes it a probe.

Two line filters become two exists subqueries, or one with both predicates if they must match the same line, which is a business question worth asking the product owner.

"You have a day. What do you cut from this design and what do you refuse to cut?"

I cut keyset pagination and ship offset with a hard cap of 100 pages, because the cursor encoding and the Window plumbing are half a day and the cap contains the damage.

I cut the projection and return a slim entity through a DTO mapper inside the read-only transaction, accepting the hydration cost for now.

I refuse to cut three things: the composed Specification that includes only active filters, because the alternative is a query with eight or :p is null clauses that the planner cannot index; the sort allow-list, because it is a security boundary; and Slice instead of Page, because the count query is the first thing to fall over at ten million rows.

Everything cut goes on a ticket with the metric that will show when it is needed.

"What is the plan-cache problem with Specifications exactly, and how do you see it?"

Each combination of active filters and sort produces a different SQL text, so eight optional filters give up to 256 WHERE shapes times four sorts, about a thousand distinct statements.

The driver's prepared-statement cache holds a few hundred per connection by default, and PostgreSQL's server-side plan cache is per prepared statement, so rare combinations never reach the prepare threshold and are planned from scratch every time, which costs a few milliseconds each.

It is visible in pg_stat_statements as a long tail of queries with low call counts and in the driver's cache eviction metrics.

In practice it is tolerable, because parse-and-plan on a simple query is cheap; it becomes a problem only if someone inlines literals, which multiplies texts by parameter values. Hibernate 6 and 7 bind parameters by default, so the shape count is the ceiling.

"How do you handle a filter that the database cannot index well, like a free-text description search?"

I take it out of this path. A like '%text%' in a Specification is a sequential scan over ten million rows, and no composite index helps.

Options in order of cost: a PostgreSQL trigram index with pg_trgm and a native predicate, which makes substring search indexable but ties the Specification to a native function; a full-text tsvector column with a GIN index, which is better for word search and still native SQL; or a search index outside the database, OpenSearch or similar, fed from the outbox, which the search endpoint queries for ids and then hydrates from the orders table by id list.

For a product-facing search screen the third is the right design, and the Specification path stays for exact and range filters.

Q98 · Scenario. "A read-only list endpoint returns entities and the JSON includes fields the client never uses; p95 latency is 800 ms and the DB is idle. Where is the time?"

Reveal answer

Strong answer Symptom: slow endpoint, idle database. Evidence: a profile of the request thread — the time will be in Hibernate hydration and Jackson, not in JDBC waits; a heap allocation profile will show entity instances, snapshot arrays, and proxy objects.

Ranked causes: one, hydration cost — for each row Hibernate instantiates the entity, populates it by reflection, creates the snapshot array, registers it in the persistence context, and creates proxies for every lazy to-one; at 5,000 rows with ten associations that is tens of thousands of objects per request; two, Jackson walking the entity graph, triggering lazy loads if OSIV is on (check the statement count) or serialising proxies and Hibernate collection wrappers through reflection; three, a wide SELECT transferring columns the client never sees, including any JSON or text columns.

Fix: a record projection selecting the six columns the client uses — no entities, no snapshots, no proxies, no persistence context growth — returned directly; readOnly = true if entities must stay for some paths; and a cap on page size.

Prevention: no @Entity return types from controllers, enforced by ArchUnit, and a latency budget per endpoint in the integration test.

Land it When the database is idle and the endpoint is slow, the time is in building objects nobody asked for — project the six columns and the 800 milliseconds go away.

Likely follow-ups
"How would you prove that the time is in hydration rather than JDBC, in one profiling session?"

Attach an async profiler in wall-clock mode to the running service and hit the endpoint fifty times, then read the flame graph.

If the wide frames are under org.hibernate.sql.results and EntityInitializer, the time is object construction; if they are under PgResultSet and socketRead, it is the database or the network.

Hibernate's own session metrics log gives a cross-check: it reports nanoseconds spent executing JDBC statements per session, and if that says 40 milliseconds while the request took 800, the remaining 760 are in Java.

A third confirmation is a heap allocation profile showing Object[] snapshot arrays and entity instances as the top allocators. Any one of the three convinces; all three take fifteen minutes.

"The projection removed 600 milliseconds. Where are the remaining 200?"

The usual suspects in order: Jackson serialisation of five thousand records, which is measurable and can be halved by streaming the response with StreamingResponseBody or by reducing the page size; the database returning five thousand rows, which is still a real transfer, visible in the JDBC time; and gzip of the response.

At that point the honest question is why the client needs five thousand rows in one response, and the answer is almost always that it does not, so page size becomes the fix.

I would cap the page at 200 with a documented default of 50 and let the client page or filter. Latency budgets are easiest to meet by returning less, and every layer downstream of a smaller result gets faster for free.

"Why does the persistence context growth matter if the request ends soon anyway?"

Three costs even for a short-lived context.

Memory churn: five thousand entities with their snapshot arrays and proxies are tens of megabytes per request, and at fifty requests per second that is gigabytes per second of allocation, which drives young-generation garbage collection pauses that show up as latency on unrelated requests.

Flush cost: if the transaction is not read-only, any query in the same transaction triggers an AUTO flush that dirty-checks every one of those entities.

And the identity map itself: each entity is hashed into the context map on load, with a cost that grows with the map.

None of these are visible with a hundred rows, all of them are with five thousand, which is why the fix for a read-only list is to never create the entities rather than to clear them afterwards.

"What would you look at if the profile showed time in the JDBC driver but the database reported the query took 5 milliseconds?"

Then the time is between the database's execution and the driver's delivery of rows: network transfer of a wide result, and driver decoding.

A SELECT that returns twenty columns including a JSON or text column for five thousand rows can be several megabytes; on a cross-zone link that alone is tens of milliseconds, and decoding text-format timestamps and numerics in the PostgreSQL driver is CPU work per value.

Confirm by checking the result size, which the driver's fetch metrics or a proxy listener can log, and by comparing the query's EXPLAIN ANALYZE time with the client-measured time.

The fix is the same projection: select six narrow columns and the bytes on the wire drop by an order of magnitude.

Q99. "How do you stream a large result set through Spring Data JPA, and what are the three settings that make streaming actually stream on PostgreSQL and MySQL?"

Reveal answer

Strong answer Declare the repository method to return Stream<T> (or use Query.getResultStream()), consume it inside a @Transactional(readOnly = true) method with try-with-resources, and detach or project so the persistence context does not accumulate — for entities, call em.detach() every N rows or use a projection.

Without three settings the driver still buffers the entire result in memory before the stream yields its first element. One: a fetch size, via @QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "1000")), which tells the driver to fetch rows in chunks.

Two, PostgreSQL: the connection must have autocommit off and the transaction must stay open for the duration, because chunked fetching uses a server-side cursor that lives in the transaction; Hikari's auto-commit: false and the read-only transaction cover this.

Three, MySQL: Connector/J streams only if the fetch size is Integer.MIN_VALUE (row-by-row streaming, which locks the connection to that statement) or if useCursorFetch=true is on the JDBC URL together with a positive fetch size, which enables server-side cursors.

Miss any of these and the "stream" is a list with a different type. Also keep the transaction short enough not to hold back VACUUM (Q39), which argues for keyset chunks over one giant stream for very large exports.

Land it Stream return type plus fetch size, plus the engine's cursor precondition — otherwise the driver buffers everything and the stream is a lie.

Likely follow-ups
"How do you verify the stream is actually streaming and not buffering?"

Two observable signals. First, time to first element: wrap the stream consumer with a timestamp before findAll() returns and at the first forEach callback; on a ten-million-row table, a real stream yields the first row in milliseconds, a buffered one after the whole result has arrived.

Second, memory: watch heap during the run; a buffered result grows by the full result size before processing starts.

On PostgreSQL you can also see the cursor from the server side: pg_stat_activity shows the statement as active for the whole duration of a streaming read, and pg_cursors lists the portal.

A test asserts the first-element latency is under a threshold with a large seeded table; it fails the day someone removes the fetch-size hint.

"What happens on PostgreSQL if a commit or rollback occurs while the stream is open?"

The server-side cursor is destroyed at transaction end, because it belongs to the transaction's portal.

The next next() on the stream asks the driver for the following chunk, and the driver gets an error like "portal does not exist", surfaced as a PSQLException from inside the stream, often wrapped in a Hibernate exception.

The typical way it happens is a nested method that calls a REQUIRES_NEW transaction on the same thread, which suspends the outer transaction but does not touch its connection, and is fine, versus code that catches an exception and the outer transaction is marked rollback-only and closed by a proxy boundary while the stream is still being read.

The rule: the stream is consumed entirely inside the method that opened the transaction, with try-with-resources, and no transaction boundaries are crossed while it is open.

"Why do you detach every N rows if the entities are read-only anyway?"

Read-only removes the snapshot but not the identity-map entry. Each streamed entity is still registered in the persistence context, so after a million rows the context map holds a million references and the entities cannot be garbage-collected until the transaction ends.

Memory grows linearly, which is precisely what streaming was supposed to avoid. Calling em.detach(entity) after processing each row, or em.clear() every thousand, drops the references. The cleaner alternative is a projection stream, because records are never registered, and there is nothing to detach.

For entity streams, Hibernate's StatelessSession with scroll() is the purpose-built tool: no context, no registration, rows arrive and are dropped.

"Is useCursorFetch on MySQL free, and what does it change on the server?"

Not free.

With useCursorFetch=true Connector/J uses the server-side prepared-statement protocol and asks the server to keep a cursor, and MySQL materialises the result into a temporary table on the server for cursor reads, which for a large result means disk I/O on the database before the first row returns.

The alternative, Integer.MIN_VALUE fetch size, streams row by row directly from the query without a temporary table, but it holds the connection to that statement until fully read and delays the release of locks and the undo log for the duration.

For an export against a replica, the row-by-row stream is usually the better choice; for a primary serving traffic, keyset chunks in short transactions avoid both problems, which is why Q100 goes that way.

Q100 · Design. "Design a nightly export of every order changed in the last day — roughly 3 million rows with lines — to a CSV in object storage, through the JPA stack, in under 15 minutes."

Reveal answer

Strong answer Requirements: bounded memory, restartable on failure, no long-lived transaction on the primary, and no interference with the morning's traffic. Design: run it against a read replica (readOnly routing) in keyset-paginated chunks — a projection query select new ExportRow(o.id, o.status, l.sku, l.quantity, ...) from Order o join o.lines l where o.updatedAt >= :since and o.id > :lastId order by o.id, l.lineNo with setMaxResults(20000), each chunk in its own short read-only transaction, writing rows straight to a streaming multipart upload so nothing accumulates.

Record the last exported id in a checkpoint table after each chunk so a crash resumes from there.

Three million orders at, say, three lines each is nine million rows; at 20,000 rows per chunk that is 450 chunks; a chunk of a projection query on an indexed range takes well under a second, so the wall time is dominated by upload bandwidth, comfortably inside 15 minutes.

Trade-offs: the join denormalises order columns per line (fine for CSV); replica lag means "last day" is measured on the replica's clock, so overlap the window by a few minutes and deduplicate by id. Alternatives: PostgreSQL's COPY ... TO STDOUT through the driver's CopyManager is several times faster and skips Hibernate entirely — the honest "do not use the ORM" choice for a pure export.

What I would not do: findAll into memory, offset pagination, or a single 15-minute cursor transaction that pins the replica's snapshot.

Land it Project, chunk by key, checkpoint, stream to storage — and if the ORM adds nothing to a table dump, let COPY do it.

Likely follow-ups
"The requirement changes: the export must be consistent as of midnight, not a moving window. What changes?"

Chunked short transactions each see a different snapshot, so a consistent point-in-time export needs either a single snapshot or a stable source.

On PostgreSQL the cleanest way is pg_export_snapshot() in one session held open on the replica, and each chunk transaction runs SET TRANSACTION SNAPSHOT '...' to read the same snapshot; that keeps one long transaction pinned on the replica, which is acceptable there but not on the primary, and vacuum on the replica is delayed for the duration.

The alternative is the outbox or change-stream approach: the warehouse already receives every change with a commit timestamp, and the export is a query over that store as of midnight.

If neither exists, filter on updated_at < midnight and accept that late-arriving updates are captured tomorrow, documenting it.

"Under time pressure, what do you cut and what stays?"

I cut the read-replica routing if it is not already wired, and run against the primary at 03:00 with the chunk size halved, because short chunks on an indexed range are gentle even on the primary.

I cut the multipart streaming upload and write to local disk, then upload, since a few gigabytes of CSV fits a pod's ephemeral volume.

I keep the keyset chunking, because offset pagination on nine million rows is the difference between minutes and hours; I keep the checkpoint table, because a restart from zero after a crash at chunk 400 is the failure that pages someone; and I keep the projection, because entity loading of nine million rows is the memory incident.

The cuts cost a bit of disk and a bit of primary load; the keeps prevent the three ways this job fails.

"Why is COPY several times faster than the JPA path, mechanically?"

Three removed layers. COPY ... TO STDOUT formats rows on the server into text or binary in one pass, streams them over the connection in large buffers, and the client writes bytes straight to the file; there is no per-row protocol message, no per-column type decoding into Java objects, and no per-row constructor call.

The JPA path receives one DataRow message per row, decodes each column into a Java value, constructs a record, and then a CSV writer re-encodes those values to text, which is the round trip from text to objects to text.

Measured on a typical order table, COPY moves rows at several hundred thousand per second per connection; the JPA projection path manages tens of thousands. When the output is a table dump, the ORM only adds decoding it will immediately undo.

"How do you know the export is complete and correct?"

Counts and a checksum, both recorded. The job computes the expected row count with one query select count(*) from order_line l join orders o ... where o.updated_at >= :since on the same snapshot rules as the export, writes the actual row count as it streams, and refuses to mark the export complete if they differ.

It also emits a manifest with the checkpoint range, the row count, an MD5 or SHA-256 of the file, and the replica's replay position at the start, so the consumer can verify and the on-call engineer can explain a discrepancy.

A reconciliation query the next day compares the manifest's count with the warehouse's loaded count and alerts on drift. Without the manifest, "the export ran" is the only thing anyone can say.

Drill · Batching & bulk work

This group tests whether you can make a write-heavy job fast with numbers you can defend, and know which knob does what.

Q101 · Scenario. "A bulk import of 5 million rows takes 6 hours through repository.saveAll(). Diagnose and give the target time with the arithmetic."

Reveal answer

Strong answer Symptom: 6 hours is 21,600 seconds for 5 million rows — 4.3 milliseconds per row, which is one network round trip each.

Evidence: the SQL log shows one INSERT per row, and for each row a SELECT if ids are assigned (merge path, Q22); heap grows over the run; batch_size is unset or the id strategy is IDENTITY. Ranked causes: one, no JDBC batching — the property is missing, or IDENTITY ids make it impossible; two, saveAll on entities with pre-set ids taking the merge path with a SELECT each; three, the whole import in one persistence context, so each flush dirty-checks everything loaded so far and GC dominates the last hours; four, on MySQL, rewriteBatchedStatements missing so batches are fake.

Fix: SEQUENCE ids with allocationSize = 50 and a matching sequence, batch_size: 50 with order_inserts, the driver's rewrite flag, flush() and clear() every 50 rows, and a commit every 5,000 — or the StatelessSession from the primer.

Target arithmetic: 5 million rows in batches of 50 is 100,000 round trips; at 4 milliseconds each that is 400 seconds, under seven minutes; with multi-row rewriting each batch is one INSERT of 50 rows and the database side is a few hundred microseconds, so the real wall time is dominated by the round trips.

Add parallel workers on disjoint chunks if the target is under two minutes. Prevention: a benchmark in CI on 100,000 rows with a time budget.

Land it Six hours is one round trip per row; batching makes it one per fifty, and the arithmetic says seven minutes before you touch anything else.

Likely follow-ups
"You applied batching and it is still slow: the log shows batches of one. What is happening?"

Four things produce batches of one with batch_size set. The id strategy is IDENTITY: Hibernate must execute each INSERT immediately to learn the generated key, so it disables batching for that entity silently; check the mapping and switch to SEQUENCE.

The statements are interleaved across entity types without order_inserts, so each type switch flushes the current batch. A flush() or a query with AUTO flush inside the loop after every entity, which executes the pending batch of one.

Or on MySQL the batch is sent but as separate statements because rewriteBatchedStatements=true is missing, in which case the driver reports batches but the server sees one INSERT per row.

The datasource proxy logs the batch size per execution, which tells me which of the four it is in one look.

"Why does flush and clear every 50 matter if you commit every 5,000?"

Because the persistence context grows until it is cleared, and every flush checks everything in it. Without a clear, at row 4,000 of a 5,000-row transaction Hibernate's flush dirty-checks 4,000 managed entities to write the next 50, and the total work per transaction becomes quadratic.

flush() sends the current batch; clear() empties the context so the next flush checks only the next 50.

Committing every 5,000 rows is about transaction size and recovery: a hundred-row transaction commits too often, a five-million-row transaction pins locks and the undo log for the whole run and loses everything on failure.

The two knobs are independent: batch and clear for memory and CPU, commit interval for durability and lock duration.

"How would you parallelise this safely to get under two minutes?"

Split the input into disjoint ranges by a natural key or by line number, and run one worker per range, each with its own transaction loop and its own sequence block, so no two workers touch the same rows or the same batch.

With allocationSize = 50 each worker fetches its own block of ids from the sequence, so ids interleave across workers but never collide.

Eight workers at seven minutes each is under a minute of wall time if the database keeps up; the limit becomes WAL write throughput and the number of concurrent inserts into the same index pages.

I watch replication lag and commit latency while scaling workers, and stop at the point where adding a worker no longer reduces wall time. Each worker checkpoints its range so a failed worker restarts alone.

"When would you skip Hibernate entirely for this import?"

When the rows need no validation or business logic beyond what the database can enforce, and the source is already tabular.

Then COPY FROM STDIN through the PostgreSQL driver's CopyManager, or LOAD DATA on MySQL, loads five million rows in a minute or two with no application round trips at all, and constraints and triggers still apply.

If there is per-row logic, a StatelessSession with insert() and JDBC batching keeps the logic in Java without the persistence context, which is the middle ground.

Full entities with cascades are right only when the import must produce aggregates with relationships and callbacks, and even then a projection-based validation pass followed by a bulk load is often faster. The decision is about what the rows need on the way in.

Q102. "What exactly do hibernate.jdbc.batch_size, order_inserts, order_updates, and batch_versioned_data each change, and what happens if only the first is set?"

Reveal answer

Strong answer batch_size lets Hibernate add up to N consecutive statements with the same SQL text to one JDBC batch before executing; with only this set, batching works whenever the flush queue happens to contain runs of the same statement — an import of one entity type batches well, but a checkout that interleaves an order insert, three line inserts and a product update produces batches of one because each table switch flushes the current batch.

order_inserts sorts the pending INSERTs by entity type (respecting parent-before-child dependencies) so all order inserts run, then all line inserts, turning the interleaved queue into two batches.

order_updates does the same for UPDATEs, and additionally sorts by primary key within a type, which reduces deadlocks between concurrent transactions updating overlapping rows in different orders.

batch_versioned_data allows UPDATEs and DELETEs with a version check into batches, using per-statement update counts to detect stale rows (Q74); it defaults to true since Hibernate 5, so you rarely set it.

None of them affect IDENTITY inserts, none of them make the driver send a real batch on MySQL without rewriteBatchedStatements, and none apply to a StatelessSession in Hibernate 7, which needs setJdbcBatchSize.

Going deeper On the stateless session: in Hibernate 6.x a StatelessSession did no JDBC batching at all, each insert() was its own statement. Hibernate 7.0, released mid-2025, added batching to it, enabled by calling setJdbcBatchSize(n) on the session, with pending statements executed on flush() or at transaction end; and as of Aug 2026 the 7.x line honours the global hibernate.jdbc.batch_size for stateless sessions by default, so the explicit setter is an override rather than a requirement. The way to verify any batching claim is not the Hibernate log but the driver's view: the datasource-proxy listener prints Batch:True, BatchSize:50 per execution, and on MySQL the general log shows one multi-row INSERT only when rewriteBatchedStatements=true is present on the URL.

Land it batch_size opens the door; order_inserts and order_updates are what walk mixed workloads through it.

Likely follow-ups
"How does Hibernate detect a stale row inside a batched versioned UPDATE, given it only gets update counts back?"

The JDBC driver returns an array of update counts, one per statement in the batch, from executeBatch().

Hibernate expects each versioned UPDATE, whose WHERE clause includes version = ?, to report exactly one affected row, and walks the array; an entry of zero means that statement's row no longer had the expected version, so Hibernate throws StaleStateException, which Spring translates to ObjectOptimisticLockingFailureException, and identifies the entity by the batch position.

The catch is the driver: if it returns SUCCESS_NO_INFO (minus two) instead of real counts, Hibernate cannot check, and that is why batch_versioned_data exists as an opt-out for drivers that behave that way. PostgreSQL's driver returns real counts; older Oracle drivers did not.

Verification is a test that updates a row concurrently and asserts the batch throws.

"What does order_inserts do with a parent-child dependency, and what can it not fix?"

It groups INSERTs by entity type while respecting foreign-key dependencies, so all Order inserts go before all OrderLine inserts, and within a type the statements are consecutive and batch together.

It cannot fix cycles: if an order references a "primary line" and lines reference the order, there is no type order that satisfies both, and Hibernate falls back to the original sequence with a possible nullable foreign key update afterwards.

It also cannot fix batches broken by an IDENTITY id anywhere in the graph, since the parent's generated id must be known before the children can be inserted, which forces immediate execution.

And it does not reorder across flushes: a flush() in the middle of the loop executes whatever is pending in whatever order was reached. So it is a sorter for one flush's queue.

"Is there a downside to order_updates?"

One subtle one. Sorting UPDATEs by entity type and then by primary key changes the order in which rows are locked within the transaction, which is what reduces deadlocks between transactions that update overlapping sets in the same sorted order.

But it also means the write order no longer matches the order of the Java changes, which matters if a database trigger or a deferred constraint depends on sequencing between two entity types, for example a balance row that must be updated before a ledger entry's trigger reads it.

Those cases are rare and usually a design smell, but when migrating an application that relied on statement order, turning on order_updates can surface a trigger bug that looks like data corruption. I enable it by default and check for triggers that read other tables.

"What batch size, and why not 1,000?"

Between 20 and 100 for ordinary entities; I use 50 to match the sequence allocation size.

Larger batches have diminishing returns and real limits: the driver buffers the whole batch in memory before sending, so 1,000 wide rows is megabytes per flush; PostgreSQL's protocol handles it, but the round-trip saving from 50 to 1,000 is under two percent of the per-row cost while the memory and the failure blast radius, one bad row failing 999 others, grow twentyfold.

MySQL's rewritten multi-row INSERT is also limited by max_allowed_packet, which a thousand rows can exceed.

The way to choose is to measure rows per second at 20, 50, 100 and 500 on the real table; the curve flattens by 50 for almost every schema I have measured.

Q103 · Scenario. "Memory blows up in a batch job that reads 2 million rows, transforms them, and writes updates. Heap dump: 4 million EntityEntry objects. Fix it two ways."

Reveal answer

Strong answer Symptom: heap proportional to rows processed; the dump shows the persistence context's entries (each holding an entity and its snapshot — two arrays per row, which is the 4 million).

Cause: every row read becomes a managed entity that stays in the context until the transaction ends, and the job runs in one transaction.

Fix one, keep the ORM: process in pages by keyset in a loop where each iteration is its own @Transactional method (called through the proxy from a non-transactional driver method), loads 1,000 entities, updates them, and returns — commit flushes the batched UPDATEs and closes the context, so memory is one page.

Inside a page, no clear() is needed because the context dies at commit; if the job must be one transaction for atomicity, flush() then clear() every 1,000 rows instead, accepting that references held across the clear are detached.

Fix two, skip the context: read with a projection or a StatelessSession scroll (session.createQuery(...).scroll() in a stateless session has no context) and write with StatelessSession.update() or a bulk update ... where id in (...); no entries, no snapshots, batched writes.

Also mark the transform-only reads as read-only to drop snapshots. Prevention: a batch framework (Spring Batch's chunk-oriented step) whose chunk size is the persistence-context bound by construction, and a heap metric alert on the job.

Land it The context is a cache with no eviction — bound it by transaction per chunk or bypass it with a stateless session.

Likely follow-ups
"Why is a transaction per chunk called through the proxy rather than a loop inside one @Transactional method?"

Because Spring's transaction boundary is the proxy around the bean, and a method calling another method on the same object bypasses the proxy, so an inner @Transactional on a private helper does nothing.

The driver method must be on a different bean, or call through the injected self-reference, and must not itself be transactional, otherwise the inner calls join the outer transaction with REQUIRED propagation and the persistence context lives for the whole job again.

The verification is simple: log TransactionSynchronizationManager.getCurrentTransactionName() at the start of each chunk, or watch the heap, which flattens into a sawtooth when the chunks really are separate transactions and climbs steadily when they are not.

The 4 million EntityEntry heap dump is what the wrong structure looks like.

"What are the consequences of flush and clear in the single-transaction variant?"

After clear() every managed entity becomes detached. Any reference the job still holds, say a Customer loaded once and reused across rows, is now a detached object; setting it on a new Order makes Hibernate throw TransientObjectException or, with a cascade, try to merge it.

Lazy collections on detached objects throw on access. So the job must reload shared references after each clear, or hold ids rather than entities, or use getReference() to obtain a fresh proxy for the id per chunk. The second-level cache is unaffected.

Because of these traps I prefer the transaction-per-chunk structure, where nothing survives the chunk by construction, and the only shared state across chunks is the checkpoint id.

"How would a StatelessSession change the memory profile, and what do you give up?"

A stateless session has no persistence context, so a scrolled read hands you one detached object per row and forgets it; heap stays flat at the size of one batch. Writes through update() go straight to SQL and batch with the batch size.

What is gone: dirty checking, so you call update() explicitly; cascades, so children are written by hand; lazy loading, so associations must be fetched in the query or left as ids; first-level caching, so two reads of the same row are two objects; and lifecycle callbacks, so auditing and Envers do not fire.

The interceptor and event listeners are also bypassed. In exchange the job behaves like plain JDBC with mapping, which for a transform-and-update pass over two million rows is exactly the right shape.

"What would the Spring Batch version look like, and what does it give you beyond the loop?"

A chunk-oriented step with a JpaPagingItemReader or, better, a JpaCursorItemReader with a keyset query, an ItemProcessor for the transform, and a JpaItemWriter with a chunk size of 1,000.

Each chunk is one transaction, the persistence context is cleared at chunk end by the framework, so the memory bound is structural rather than a discipline.

Beyond the loop it gives restartability from the job repository's last committed chunk, skip and retry policies per exception type, metrics per step, and a record of every run. The cost is the framework's own metadata tables and a learning curve.

For a one-off job the loop is fine; for a nightly job with an on-call rota, the restart and skip semantics pay for themselves the first time it fails at two in the morning.

Q104. "When does a JPQL bulk UPDATE beat loading entities and letting dirty checking write, and what do you lose?"

Reveal answer

Strong answer A bulk JPQL statement — update Order o set o.status = 'ARCHIVED' where o.status = 'SHIPPED' and o.createdAt < :cutoff — becomes one SQL UPDATE that the database executes set-wise: no rows travel to the application, no entities are instantiated, and the whole change is one round trip whether it touches ten rows or ten million.

Loading entities costs a SELECT of every row, hydration, snapshots, and one UPDATE per row at flush (batched at best into N/50 round trips).

The bulk path wins whenever the change is expressible as a SQL expression over the rows and does not depend on per-row Java logic — archiving, price recalculations by formula, flag flips, deletes by predicate.

You lose: lifecycle callbacks and entity listeners (no @PreUpdate, no Spring Data auditing, no Envers revision); optimistic locking unless you write update versioned; cascades and orphan removal; and consistency with the persistence context, which keeps stale copies until cleared.

You also lose the ability to run per-row business rules, which is precisely the case where entities are right.

A sound split: entity-based writes for user actions on one aggregate, bulk statements for administrative and scheduled set operations, and the bulk path always in its own transaction with clearAutomatically.

Land it If the change is a predicate and an expression, say it in one statement; if it is a rule per row, load the rows — and never mix the two in one context.

Likely follow-ups
"What does clearAutomatically and flushAutomatically on @Modifying actually do, and which one is dangerous?"

flushAutomatically = true flushes the persistence context before the bulk statement runs, so pending entity changes reach the database first and the bulk update sees them; without it, an earlier in-memory change to a matching row could be overwritten at commit by the dirty check writing the stale entity state back.

clearAutomatically = true clears the context after the statement, so entities loaded before it are not stale copies. The dangerous one is clearAutomatically when the caller holds references: those become detached, and unflushed changes on them are lost silently, since a clear discards pending state.

So the safe combination is both flags, and the bulk method called from a service method that holds no entity references, ideally its own transaction.

"How does update versioned work, and what does it look like in SQL?"

The JPQL update versioned Order o set o.status = 'ARCHIVED' where ... makes Hibernate add version = version + 1 to the SET clause, so every row the bulk statement touches gets a new version, and any concurrent transaction holding a stale entity with the old version fails its next dirty-check UPDATE with a stale-state exception.

It is a Hibernate extension, not standard JPQL, and it also bumps timestamp versions when @Version is a timestamp. What it does not do is check versions itself, because a bulk statement has no expectation of which version each row should have.

It is the minimum to keep optimistic locking honest across a bulk write; without it, a user's entity-based save after the archive silently overwrites the archived status with the old one.

"The scheduled job's bulk update takes a lock on ten million rows for two minutes. What next?"

Chunk the bulk statement. A single UPDATE over ten million rows holds row locks and generates undo and WAL for the whole run, and any user transaction touching one of those rows waits.

Rewrite it as a loop of update orders set status = 'ARCHIVED' where id in (select id from orders where status = 'SHIPPED' and created_at < :cutoff order by id limit 5000) as a native query, each in its own short transaction, with a brief sleep between chunks and a stop condition when the update count is zero.

Each transaction holds locks for milliseconds. Keep an index that makes the subquery a range scan. The total work is the same, but no user waits longer than one chunk, and a failure loses one chunk rather than two minutes of work.

"Can you get auditing for bulk updates without loading entities?"

Not through JPA callbacks, so it has to be explicit. Two ways. Write the audit in the same statement's transaction: on PostgreSQL WITH updated AS (UPDATE orders ... RETURNING id, status) INSERT INTO order_audit (order_id, new_status, changed_by, changed_at) SELECT id, status, :actor, now() FROM updated, which is one native statement that records every affected row atomically.

Or use a database trigger that writes the audit row on every UPDATE regardless of who issued it, which also covers writes from other tools and migrations.

Envers cannot see bulk statements, so if Envers is the audit of record, bulk updates on audited entities are simply not allowed, and that rule goes in the golden path.

The interviewer wants to hear that you know the callbacks are gone and have a concrete replacement.

Q105 · Design. "Design a nightly re-pricing job that applies a rule engine's Java logic to 8 million product rows and must finish inside a 30-minute window."

Reveal answer

Strong answer Requirements: per-row Java logic (so a pure SQL update is out), 8 million rows in 1,800 seconds — 4,400 rows per second sustained — restartable, and no lock storm on a table that customers read all night.

Design: partition the id range into, say, 16 ranges by keyset and run 16 workers (threads or pods), each processing chunks of 2,000 rows: a read-only projection query for the chunk's inputs (id, cost, category, current price), the rule engine in memory, then writes through a StatelessSession or a batched @Modifying update with a CASE expression, or — simplest and fast — StatelessSession.update() per row with setJdbcBatchSize(200), only for rows whose price actually changed (typically a fraction).

Each chunk is its own short transaction, so row locks are held for milliseconds and readers under MVCC never block; a checkpoint row per range records the last id.

Arithmetic: if 20 percent of rows change, that is 1.6 million updates in batches of 200 — 8,000 round trips, spread across 16 workers, seconds of database time; the wall clock is dominated by reading and by the rule engine, which parallelises.

Trade-offs: parallel writers on one table raise WAL and replication volume, so run it when replicas are quiet and watch lag; the stateless session bypasses callbacks and auditing, so write an explicit price-history row per change in the same batch.

What I would not do: a Spring Batch job with an entity-based writer in one JVM, which is single-threaded round trips and would need every one of the 30 minutes for reads alone.

Land it Partition by key, read projections, write only changes in stateless batches, commit per chunk — the job's speed is round trips divided by workers.

Likely follow-ups
"The requirement changes: the rule engine needs the product's category tree and supplier contracts, not just four columns. What changes?"

The read side gets heavier and the design has to keep it off the per-row path.

The category tree and supplier contracts are reference data shared by many products, so each worker loads them once per chunk, or once per run into an in-memory map keyed by category id and supplier id, and the per-row projection stays four columns plus the two foreign keys.

That keeps the read at one indexed query per chunk. If the reference data is large, a READ_ONLY second-level cache region or a plain Caffeine map does the job for the run's duration.

What I would not do is fetch the tree per product through lazy associations, which turns a 4,400 rows-per-second budget into an N+1 across sixteen workers and blows the window.

"The job ran at 2,000 rows per second, half the target. What do you check, in order?"

First, whether the workers are really parallel: sixteen threads sharing a Hikari pool of ten means six wait for a connection at any moment; the pool must be at least the worker count.

Second, the batch size per statement from the proxy log, because a stateless session with batching not enabled is one round trip per update.

Third, where the time goes per chunk: read query, rule engine, or write, from timings around each phase; if the read is slow, the keyset range query has lost its index; if the engine is slow, add workers, since it is CPU; if the write is slow, the database is the limit and I look at commit latency and WAL. Fourth, lock waits on the products table from the online traffic.

Each check is a number, and the first one that is wrong is the fix.

"Under time pressure, what do you cut?"

I cut the partitioned workers and run four instead of sixteen, because the coordination of ranges and checkpoints per worker is the fiddly part, and four workers at the measured rate is a 20-minute run that still fits the window with margin.

I cut the price-history write into the same batch and let a database trigger on products.price write history instead, which is one migration and covers every writer.

I keep the projection read, the stateless batched write, the transaction per chunk, and the checkpoint per worker, because those are what make it restartable and gentle on readers.

If the deadline is really tight, I also keep the "only rows whose price changed" filter, since it typically cuts the write volume by four-fifths for free.

"How does the CASE-expression batched update compare with per-row stateless updates?"

A single UPDATE products SET price = CASE id WHEN ? THEN ? WHEN ? THEN ? ... END WHERE id IN (...) for 200 rows is one statement and one round trip, versus a JDBC batch of 200 single-row UPDATEs which is one round trip but 200 statement executions on the server.

The CASE version is faster on MySQL, where batch rewriting does not apply to UPDATE; on PostgreSQL the difference is small because the batched statements are pipelined.

The CASE version's costs are a long parameterised statement that the planner handles fine but the driver cache dislikes, and a fixed shape per chunk size. I default to the stateless batched update for readability and reach for CASE, or on PostgreSQL an UPDATE ... FROM (VALUES ...), when the measurement says the write is the bottleneck.

Drill · Caches, statistics & connections

This group tests whether you can say when a cache helps, when it lies, and how to prove either with numbers.

Q106. "What does the second-level cache actually store, which operations use it, and which ones bypass it entirely?"

Reveal answer

Strong answer The L2 cache stores, per cacheable entity type, a region mapping primary key to a disassembled state — an array of the entity's column values, not the Java object — plus, for cacheable collections, a region mapping owner id to the list of element ids.

It is shared across all sessions in the JVM (or across nodes if the provider is distributed).

Operations that use it: find() and getReference() by id, resolution of a to-one association when the target is cached, and initialisation of a cached collection — all of which look up by key.

Operations that bypass it: every JPQL, criteria and native query, because a query's result depends on predicates the cache cannot evaluate; the query goes to the database, and only the hydration of the returned ids can be served from the cache when the query selects entities.

Bulk updates and native statements bypass and, by default, invalidate the regions of the affected tables.

Writes through the session update the cache according to the concurrency strategy — READ_ONLY never updates, NONSTRICT_READ_WRITE evicts and lets the next read repopulate, READ_WRITE uses soft locks so a concurrent read during the write cannot cache stale data, and TRANSACTIONAL requires a JTA-capable provider.

Spring Boot enables it with spring.jpa.properties.hibernate.cache.use_second_level_cache: true, a region factory (jcache), and jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE so only @Cacheable types participate.

Land it L2 is a by-id cache of column arrays — queries never read it, and that single fact decides whether it will help you.

Likely follow-ups
"Walk through exactly what happens on em.find(Product.class, 42) with the L2 cache on."

Hibernate checks the persistence context first; a hit returns the managed instance with no cache or database access.

On a miss it computes the cache key from the entity name and id, asks the region for that key, and if present gets the disassembled state array, reassembles it into a new entity instance, registers it in the persistence context, and returns it, with no SQL. Only on a cache miss does it run the SELECT, hydrate the row, and, if the concurrency strategy allows, put the disassembled state into the region.

Lazy associations inside the cached state are stored as ids and become proxies on reassembly; collections are only cached if the collection role itself is annotated @Cache. The statistics show it: getSecondLevelCacheHitCount() increments on the second path, getEntityLoadCount() on the third.

"Why store a disassembled array rather than the object?"

Because the cache is shared across sessions and entity instances are not.

A managed entity belongs to one persistence context, holds proxies bound to one session, and may be mutated by that session's code; sharing the object would leak one transaction's uncommitted state into another's and tie the cache to a session that will close.

The disassembled form is a plain array of immutable values keyed by property position, safe to hand to any session, cheap to serialise for a distributed provider, and small. Each session that hits the cache builds its own instance from the array.

This is also why the L2 cache never saves object-construction cost, only the SQL round trip and the hydration from a result set; if construction is the bottleneck, the cache does not help.

"What is the difference between NONSTRICT_READ_WRITE and READ_WRITE in a race, concretely?"

Take a write to product 42 committing at the same moment another session reads it.

With NONSTRICT_READ_WRITE, the writer evicts the entry after commit; if the reader missed the cache just before the eviction and loaded the old row from the database, it may put the old state back into the cache after the writer's eviction, and the stale value lives until the next write or expiry.

With READ_WRITE, the writer places a soft lock on the key before the transaction commits; a reader that misses during the lock window is allowed to read from the database but is refused permission to put its result into the cache, and the lock is released after commit, so the stale put cannot happen.

READ_WRITE costs one extra cache write per update; the strictness is what you pay for.

"Does a JPQL query that selects entities benefit from the cache at all?"

Partially, and only in one form. If the query selects only ids, select o.id from Order o where ..., and the code then calls find() per id, each find is served from the cache; that is what the query cache automates.

If the query selects the entities themselves, the SQL already brought back every column, so Hibernate hydrates from the result set and the cache is only written to, not read.

The exception is associations: a query returning orders whose lazy customer is in the cache resolves those proxies from the cache without SQL when touched.

So the practical benefit is for the to-one targets of query results, reference data like customers and products, which is where READ_ONLY regions on immutable types earn their keep.

Q107 · Scenario. "After enabling the second-level cache on Product, two pods serve different prices for the same SKU for up to ten minutes. Explain and fix."

Reveal answer

Strong answer Symptom: stale reads bounded by a time window on some nodes. Evidence: the window matches the cache region's time-to-live; the pod that performed the price update always serves the new price; other pods serve the old one until expiry.

Cause: the L2 cache is per JVM with an in-process provider (Ehcache, Caffeine); a write on pod A updates or evicts pod A's entry, and pods B and C know nothing until their entries expire.

Ranked fixes: one, if the data is reference data updated rarely, keep the local cache but make writes publish an eviction — a lightweight "product changed" event on a topic that every pod consumes by calling sessionFactory.getCache().evict(Product.class, id); two, a distributed provider (Infinispan or Hazelcast in invalidation mode) so an update on one node invalidates the others, at the cost of a cluster to run; three, shorten the TTL to seconds for entities where staleness has a price, which is honest but weakens the cache; four, remove Product from the L2 cache and cache the read model at the HTTP or CDN layer with explicit invalidation, which is often what "catalogue caching" should have been.

Also check that nothing writes prices outside Hibernate — a bulk SQL or another service — because those writes evict nothing anywhere. Prevention: a cache-consistency test with two application contexts against one database.

Land it A local L2 cache on a multi-node deployment is a promise to serve stale data for one TTL — invalidate across nodes or cache somewhere that can.

Likely follow-ups
"You published eviction events and a pod still served the old price for a minute. What next?"

Ordering and timing. The eviction event must be published after the transaction commits, not inside it; if it is sent inside, the receiving pod evicts and immediately reloads the row before the commit is visible, caching the old price again, which is the classic invalidate-before-commit race.

Move the publish into a TransactionSynchronization.afterCommit callback or an outbox. Then check that the consumer on every pod is actually running and keeping up: a consumer group that has one pod lagging is a pod that serves stale data for its lag.

And check that the event carries the entity type and id and the receiving code calls evictEntityData(Product.class, id) rather than a region-wide clear that thrashes.

If all of that is right and a minute still elapses, the remaining window is the consumer's poll interval, which is a setting.

"How would you write the two-context cache-consistency test?"

One JVM, two Spring application contexts booted against the same Testcontainers database, each with its own SessionFactory and its own local cache, which models two pods.

The test loads product 42 through context A so it is cached there, updates the price through context B and commits, then reads through context A and asserts the new price within a bounded time.

Without cross-node invalidation the assertion fails, which is the point: it fails on the local-cache design and passes once the eviction event or the distributed provider is wired, using an embedded broker or a direct call to the eviction handler. It runs in a few seconds.

Most teams have never had a test that models two nodes, and this is the test that would have caught the ten-minute staleness before a customer did.

"The write path is Hibernate, but a nightly price import uses COPY. How do you keep the cache honest?"

The import bypasses Hibernate, so no region is evicted anywhere.

The reliable option is a global eviction after the import: the job's last step calls an admin endpoint on every pod, or publishes one event, that runs sessionFactory.getCache().evictEntityData(Product.class) for the whole region, which is cheap once a night and simply forces reloads.

The second option is a change-data-capture stream on the products table feeding the same eviction consumer, which covers every writer forever, including one nobody told you about.

What I would not accept is a TTL as the only mechanism, since a ten-minute TTL is the incident being discussed.

And I would add the rule to the golden path: any writer outside Hibernate on a cached table must evict, or the table is not cacheable.

"What does invalidation mode versus replication mode mean in Infinispan or Hazelcast here?"

In invalidation mode each node keeps its own local cache, and a write on one node sends a small message telling every other node to remove that key; the next read on those nodes misses and reloads from the database.

Cheap network traffic, no shared state, and the staleness window is the message latency, milliseconds.

In replication mode each write sends the new value to every node, so every node's cache stays populated, at the cost of copying every entity change across the cluster, which for a write-heavy table floods the network.

For an ORM second-level cache, invalidation is almost always right, because a reload by primary key is cheap and keeps the cache small. Both require the cluster's membership and networking to be operated, which is the cost the answer warned about.

Q108. "Why does the Hibernate query cache often make things slower, and what is the one workload where it shines?"

Reveal answer

Strong answer The query cache stores, keyed on the query text plus parameter values, the list of ids the query returned and a timestamp.

On a hit it must then resolve every id to an entity — from the L2 cache if the entity type is cached there, otherwise with one SELECT by id per row, which turns a single query into an N+1 against the database.

Its invalidation is coarse: the update-timestamps region records the last write time per table, and any cached result whose tables have a newer write timestamp is invalid — so one INSERT into orders anywhere invalidates every cached orders query for every parameter set.

On a table with steady writes the hit rate approaches zero while the bookkeeping (a timestamp check and a region write per query, per write) is paid on every operation.

It shines in one workload: a query over a table that changes a few times a day, returns entities that are themselves in the L2 cache, and is executed with a small set of parameter values by many requests — a menu of categories, a country list, a set of feature flags per tenant.

Enable it per query with setCacheable(true) and a named region, never globally, and confirm with Statistics.getQueryCacheHitCount() that it hits.

Land it The query cache is invalidated by any write to the table and hydrates by id — worth it only for static data whose entities are also cached.

Likely follow-ups
"What is the update-timestamps region and what does it cost on every write?"

It is a special cache region that maps each table name to the timestamp of the last transaction that modified it. Before any write to a table, Hibernate pre-invalidates the entry by writing a timestamp in the future, and after commit writes the actual commit time.

When a cached query result is looked up, Hibernate compares the result's stored timestamp against the entries for every table the query touches; if any table's timestamp is newer, the result is discarded.

The cost is two region writes per table per write transaction, which on an in-process cache is microseconds but on a distributed provider is two cluster messages per commit, whether or not anyone runs cached queries.

That overhead is why enabling the query cache globally on a write-heavy system slows every transaction a little for no benefit.

"Why does one insert invalidate every cached query on the table rather than just the affected ones?"

Because the cache cannot evaluate predicates. A cached result for status = 'OPEN' is just a list of ids plus a timestamp; Hibernate has no way to know whether a new row would have matched that WHERE clause without re-running the query, which defeats the purpose.

So the only safe rule is coarse: any change to a table might have affected any query over it, therefore all are invalid. The same coarseness applies to updates and deletes.

A read-model cache that is invalidated by key from the write path is precise because the application knows which keys a change affects; the query cache cannot know, which is the structural reason it fits only near-static tables.

"How do you set up the one workload where it shines, end to end?"

Take the category menu. The Category entity gets @Cacheable @Cache(usage = READ_ONLY) and @Immutable, so the ids from a query hit resolve without SQL. The repository method gets @QueryHints(@QueryHint(name = HibernateHints.HINT_CACHEABLE, value = "true")) and a region name hint, and hibernate.cache.use_query_cache: true is set.

Category writes go through an admin job that finishes by evicting the query region and the entity region on every node.

Then I verify with statistics: getQueryCacheHitCount() should climb and getQueryCachePutCount() should plateau after the first request per parameter set; if puts keep rising, invalidation is firing more than expected and something writes to the table.

That last number is the proof that the workload really is static.

"What happens if the query returns entities that are not in the L2 cache?"

The hit turns into a hydration loop. Hibernate has the list of ids and, for each one, needs the entity; it checks the persistence context, then the L2 region, and finding neither, issues select ... where id = ? per id.

A cached result of 200 rows becomes 200 SELECTs, which is strictly worse than running the original query once.

Hibernate 6 and 7 batch these loads if batch fetching is configured for the type, so it becomes 200 divided by the batch size, but it is still extra round trips compared to a cache miss.

This is why the rule is that a cacheable query must return only cacheable entities or scalar values. A scalar query, ids and names, is safe because the result list is the answer itself.

Q109 · Design. "Design the caching strategy for a product catalogue read 20,000 times per second and updated a few hundred times per hour, served by 30 pods."

Reveal answer

Strong answer Requirements: sub-millisecond reads, staleness bounded to a few seconds after a price change, no thundering herd on invalidation, and the database protected from the read volume. Design in layers.

Layer one, the database stays the source of truth with read replicas for the residual load.

Layer two, a shared Redis cache of read models — the JSON the API returns per product and per category page — keyed by id and version, with a TTL of an hour as a safety net and explicit invalidation: every catalogue write goes through the orders-catalogue service, which persists via JPA and, from an outbox row processed after commit, deletes the affected keys and publishes a "product changed" event.

Layer three, an in-process Caffeine cache of a few thousand hot read models per pod with a TTL of five seconds, so 30 pods absorb the hottest keys without a Redis hop, and the five-second TTL bounds cross-pod staleness without needing cluster invalidation.

Hibernate's L2 cache has a narrow role here: READ_ONLY regions for genuinely static reference entities (currencies, categories) that the write path joins to.

Herd protection: request coalescing on cache miss (Caffeine's get(key, loader) does it per pod; a short lock in Redis per key does it across pods). Trade-offs: three layers to reason about; a change visible within roughly five seconds rather than instantly.

What I would not do: L2-cache the Product entity with READ_WRITE across 30 pods and rely on TTL, which is Q107; or cache at the entity layer at all when the unit of reuse is the API response.

Land it Cache the response, not the entity; invalidate from the write path after commit; bound cross-pod staleness with a short local TTL.

Likely follow-ups
"The requirement changes: price must be exact within one second, not five, and the business will not accept a race. What changes?"

The local five-second Caffeine layer has to go, or shrink to sub-second, because it is what bounds cross-pod staleness by time.

The design becomes: Redis as the single shared cache, invalidated by the outbox after commit, and every pod reads Redis on each request with no local layer, so a change is visible after the outbox processes it, typically within a few hundred milliseconds.

To close the remaining window, the price-sensitive operation, checkout, does not trust the cache at all: it reads the price from the database inside the order transaction and validates it against what the client saw, rejecting with a "price changed" response if different.

That makes the cache a display optimisation and the database the arbiter, which is the only way to say "no race" honestly.

"You have a week. What do you cut?"

I cut the Redis layer and ship Caffeine per pod with a five-second TTL plus request coalescing, in front of a read-replica projection query.

Thirty pods with five-second TTLs on a few thousand hot products means each pod asks the replica once per product per five seconds, which for 20,000 requests per second across the fleet is a few hundred database queries per second, well within a replica's budget.

I cut the outbox-driven invalidation and rely on the TTL, which bounds staleness at five seconds, which the requirement allows. I keep the read-model shape, the JSON per product, so that adding Redis later changes only the loader.

What I do not cut is the herd protection, because a TTL expiry across thirty pods at once without coalescing is a thirty-times spike on the replica every five seconds.

"What does request coalescing look like in Caffeine and across pods in Redis?"

In Caffeine, cache.get(key, loader) guarantees that concurrent callers for the same missing key block on one loader invocation, so a hundred requests for a cold product produce one database query per pod; that is built in.

Across pods, Redis has no such guarantee, so thirty pods missing at once each query the database.

The standard fix is a short lock per key: SET lock:product:42 1 NX PX 200; the pod that wins loads and writes the value, the others wait briefly and re-read Redis, with a fallback to loading themselves if the lock expires.

An alternative is serving the stale value while one refresh runs in the background, which Caffeine supports with refreshAfterWrite, and which for a catalogue is usually better than blocking. Both are ten lines of code and prevent the invalidation storm.

"How do you verify the cache is doing what the design says in production?"

Four metrics per layer. Hit ratio per cache: Caffeine exposes stats through Micrometer's CaffeineCacheMetrics, and Redis hits are counted by the loader; a local hit ratio under 90 percent on a hot catalogue means the TTL or the size is wrong.

Staleness: a synthetic check that updates a test product's price and measures the time until every pod's response reflects it, run every few minutes and graphed. Database load: queries per second on the replica for the catalogue queries, which should be flat regardless of traffic.

And the herd signal: a percentile of loader latency spiking at TTL boundaries means coalescing is broken. Those four graphs on one dashboard tell the story; without them "the cache works" is a belief.

Q110 · Scenario. "You need to prove to a sceptical lead that a change reduced database work. Which Hibernate statistics and logs do you show, and how do you capture them per request?"

Reveal answer

Strong answer Enable hibernate.generate_statistics: true and obtain sessionFactory.getStatistics().

Per request, the numbers that matter are getPrepareStatementCount() (statements sent), getEntityLoadCount() and getEntityFetchCount() (rows hydrated versus loaded lazily as a secondary fetch — a high fetch count is the N+1 signature), getCollectionFetchCount(), getSecondLevelCacheHitCount() and miss count, getQueryExecutionMaxTime() with getQueryExecutionMaxTimeQueryString() for the slowest query, and getFlushCount().

Because the statistics object is global, capture per request by reading the counters before and after in a servlet filter and logging the delta with the request id, or set org.hibernate.stat to DEBUG, which logs a per-session summary at session close — "Session Metrics: 1,234,000 nanoseconds spent executing 3 JDBC statements; 0 spent executing 0 JDBC batches" — that you can grep by request.

For the lead, show the before-and-after of statements per request and JDBC time per request from that log, plus one SQL log excerpt demonstrating the N+1 gone. In tests, a datasource proxy with assertSelectCount makes the proof permanent.

Keep statistics off in steady-state production or sample them, since they add a small per-operation cost.

Land it Statements per request and entity fetch count are the two numbers that settle the argument; the session metrics log gives them per request for free.

Likely follow-ups
"Statistics are global. How exactly do you make the per-request delta correct with concurrent requests?"

With a global counter and concurrent requests, a before-and-after delta includes other requests' statements, so the filter approach is only accurate under a single-request test.

In production, the per-session numbers are the reliable ones: Hibernate's SessionStatistics and the session metrics log are scoped to the session, and since a request's transaction is one session, they are per request by construction.

Programmatically, an Interceptor or a StatementInspector registered on the session factory counts statements on the current thread into a request-scoped holder, which the filter logs with the request id. The datasource proxy's QueryCountHolder does the same per thread.

So for the sceptical lead, the demonstration uses the session metrics line, and the dashboard uses the thread-scoped listener; the global counters are for rates, not per-request attribution.

"What is the overhead of generate_statistics, and would you leave it on?"

It is a set of atomic counters incremented per operation, plus a System.nanoTime() pair around each statement and each query execution.

On a service doing a few thousand statements per second the cost is well under one percent of CPU, and I leave it on, because the entity fetch count and the statements-per-request metric are the two numbers that catch regressions.

The expensive parts are elsewhere: getQueryExecutionMaxTimeQueryString() keeps per-query-string maps that grow with the number of distinct query texts, which with unpadded IN lists or dynamic criteria can become a memory concern, and turning on org.hibernate.stat DEBUG logs a line per session, which at high traffic is a log-volume cost.

Metrics on, per-session log sampled, and clear the statistics daily if the query map grows.

"The lead says the before-and-after were measured on different data. How do you make the comparison fair?"

Fix the dataset and replay.

Take a snapshot of production-shaped data into a staging database, run the same recorded requests, a few hundred from an access log, against the old build and the new build in turn, and compare statements per request and JDBC time per request as distributions, not single numbers.

Both builds see identical rows, so the only variable is the code.

For the strongest argument, the integration test with assertSelectCount on seeded data is the same fair comparison in miniature: it fails on the old build and passes on the new one, and it is reproducible by anyone on the team.

A sceptic is answered by a test they can run, not by a graph from a day they did not observe.

"Beyond counts, which single log excerpt convinces fastest?"

The SQL log of one request, before and after, with org.hibernate.SQL at DEBUG and bind values at TRACE from org.hibernate.orm.jdbc.bind, formatted with hibernate.format_sql: true.

Before: one SELECT on orders and then forty near-identical SELECTs on order_line, each with a different bound id, in a visible column of repeated text. After: one SELECT with the join, or one SELECT with an IN list of forty ids.

Anyone can read that, including a lead who has never opened Hibernate's documentation. I put the two excerpts side by side in the pull request with the counts, and the argument is usually over. Numbers need trust; the log is the thing itself.

Q111. "How would you size the HikariCP pool for a JPA service, and how does the persistence context change the calculation compared with plain JDBC?"

Reveal answer

Strong answer Start from the database, not the service: a PostgreSQL instance handles a few hundred active connections well and degrades beyond that; total connections equal pool size times pod count, so with 40 pods a pool of 10 is 400 sessions, which is already the limit — the fleet arithmetic in E8.

HikariCP's own guidance is cores times two plus spindles for a CPU-bound database, which often means a pool of 10 to 20 per service is generous.

The persistence context changes the calculation through hold time: with plain JDBC a connection is borrowed for a statement or a short explicit transaction; with JPA the connection is held for the whole @Transactional method by default, including any remote calls or CPU work in it, so the effective demand is transactions in flight, not statements in flight.

Reduce hold time first — delayed acquisition with provider_disables_autocommit, no I/O in transactions, read-only paths short — and only then size.

Measure with Hikari's metrics: hikaricp.connections.pending should be zero, connections.usage (hold time) should be milliseconds; if usage is high the fix is in the transactions, not the pool. Set connection-timeout low (a few seconds) so a saturated pool fails fast rather than queuing 30 seconds.

With virtual threads on Java 21 the thread count is no longer the cap, so the pool becomes the hard concurrency limit and must be tuned deliberately.

Land it Size from the database's limits divided by pods, then make transactions short enough that ten connections are plenty — hold time is the variable you control.

Likely follow-ups
"What does provider_disables_autocommit do, and how does it shorten connection hold time?"

By default Hibernate borrows the connection when the transaction begins, because it must set autocommit to false on it, and holds it until commit.

If Hikari is configured with auto-commit: false so every pooled connection is already in that state, then setting hibernate.connection.provider_disables_autocommit: true tells Hibernate it can skip that step and delay acquiring the connection until the first statement actually needs it.

A service method that does a remote call, some validation, and then a query holds the connection only from the query onward. The saving is the pre-statement portion of every transaction.

The trap is misconfiguration: if Hikari's autocommit is actually true and the property is set, statements run in autocommit mode and the transaction is not a transaction, so the two settings must be set together and verified with a rollback test.

"Hikari pending is nonzero but usage is low. What does that combination mean?"

Short hold times but too many borrowers at once, which is a concurrency spike rather than slow transactions.

Either traffic genuinely exceeds the pool's throughput, which at a 5-millisecond hold is 2,000 transactions per second for a pool of ten, or many transactions start simultaneously in bursts, for example a scheduled job that fans out a hundred tasks.

The fix is admission control ahead of the pool: a bounded executor for the job, a rate limit on the endpoint, or a modestly larger pool if the database has headroom.

What the combination rules out is the usual advice of shortening transactions, since they are already short; a larger pool is justified here in a way it is not when usage is high. The two metrics together decide which knob to turn.

"How does a read replica change the sizing?"

It splits the pool. With routing on readOnly, there are two datasources and two Hikari pools, and each is sized from its own database's limit and its own workload's hold time.

Read transactions are usually shorter and more numerous, so the replica pool is often larger than the primary's, and the primary pool shrinks because it only carries writes. The total connections per pod go up, so the fleet arithmetic is done per database.

A subtle cost: a request that reads then writes uses two connections from two pools in sequence, and the routing decision is made at transaction start, so a write inside a read-only transaction fails or goes to the replica depending on the wrapper.

The pools are sized and monitored separately, with pending and usage per pool.

"Why not just set the pool to 100 and stop worrying?"

Because the database has a fixed amount of CPU and I/O, and a hundred connections per pod across forty pods is four thousand sessions contending for it, each with its own backend process on PostgreSQL consuming memory and scheduler time.

Beyond the point where active connections exceed cores times a small factor, throughput falls as the database spends its time context-switching and waiting on locks between more transactions than it can serve, and latency rises for everyone.

A small pool is a deliberate queue in the application, where waiting costs a thread and nothing else; a huge pool moves the queue into the database, where waiting costs memory, lock contention, and everyone's latency.

HikariCP's own documentation makes this argument with benchmarks, and it is the right one.

Q112 · Scenario. "Every query is 30 percent slower after moving to Java 21 virtual threads with Spring Boot 3.5, and Hikari shows connection waits that did not exist before. What changed?"

Reveal answer

Strong answer Symptom: higher latency and new pool contention after enabling spring.threads.virtual.enabled: true.

Evidence: request concurrency went up — Tomcat's 200-thread cap no longer limits in-flight requests, so more transactions run at once than the pool of 10 can serve, and the extra requests wait for connections; also check for pinning, where a virtual thread blocks its carrier inside a synchronized block during JDBC I/O (older PostgreSQL and MySQL drivers had such blocks; JDK 21 pins on synchronized, JDK 24 and later do not).

Ranked causes: one, the pool is now the concurrency bottleneck — previously 200 platform threads were an implicit admission control that kept transactions in flight at or below the pool size; two, driver pinning reducing effective parallelism, visible with -Djdk.tracePinnedThreads; three, more concurrent transactions on the database causing more lock waits.

Fix: treat the pool as deliberate admission control — size it for the database's capacity, set a short connection-timeout, and add a semaphore or rate limiter in front of the transactional layer so excess requests queue in the application rather than in the pool; update the JDBC driver to a version without synchronized I/O paths.

Prevention: load test the virtual-thread switch with Hikari metrics on the dashboard, because "unlimited threads" moves the bottleneck to the database.

Land it Virtual threads remove the thread cap that was quietly protecting your pool — the pool is now your admission control, so size and time out on purpose.

Likely follow-ups
"How do you detect pinning in production, and what changed in JDK 24?"

On JDK 21 to 23, a virtual thread that blocks inside a synchronized block or method pins its carrier thread, so the carrier cannot run other virtual threads, and with a small carrier pool a handful of pinned JDBC reads stall the whole application.

The -Djdk.tracePinnedThreads=full flag prints a stack trace on each pinning event, and JFR records jdk.VirtualThreadPinned events with the stack, which is the production-safe way to find them.

JDK 24, through JEP 491, changed the implementation so that blocking inside synchronized no longer pins; the virtual thread unmounts as it does for ReentrantLock. As of Aug 2026, on JDK 25 the pinning cases left are native frames and class initialisers.

So the fix for driver pinning is either a driver release without the synchronized paths or a JDK upgrade.

"The retry didn't fix the connection waits. Where does the extra concurrency actually come from?"

From the removal of the platform-thread cap at every layer that used one. Tomcat's request threads were capped at 200; with virtual threads each request gets its own thread and the cap is effectively gone unless server.tomcat.threads.max still applies to the acceptor side.

Async executors that were bounded by pool size now run every submitted task at once. Scheduled jobs that fanned out across a fixed pool now fan out completely.

Each of those was an implicit admission control, and each removed cap adds concurrent transactions competing for the pool of ten.

The way to see it is Hikari's active plus pending over time against request rate; if pending appears at the same request rate as before, the concurrency multiplier is internal.

The fix is explicit bounds where the implicit ones were: a Semaphore around the transactional layer, bounded executors, and a pool sized for the database.

"Should the pool be larger under virtual threads, then?"

Only if the database has headroom, and that is a database question, not a thread question. Virtual threads make the application able to hold more transactions in flight, but the database can still only execute as many as its cores and I/O allow.

If Hikari usage shows transactions completing in a few milliseconds and pending is high, and the database's CPU is at 40 percent, a larger pool converts waiting into throughput and is right.

If the database is at 90 percent, a larger pool converts waiting in the application into waiting in the database, and latency rises.

So the sequence is: measure database utilisation, then size the pool to keep it under a target, then bound application concurrency to the pool size plus a queue with a short timeout. The pool is a knob on the database, held from the application.

"What is the failure mode if connection-timeout is left at the default 30 seconds?"

Every request that cannot get a connection waits up to 30 seconds and then fails, and meanwhile its caller has timed out at 5 seconds and retried, adding another waiter.

Under a spike the pool queue fills with requests whose clients have already gone, the service reports timeouts across every endpoint including the ones that do not touch the database, and recovery takes minutes after the spike ends because the queue drains slowly.

With a 2-second timeout, excess requests fail fast, the queue stays short, clients get a clear 503 and back off, and the healthy portion of traffic keeps flowing. The setting is spring.datasource.hikari.connection-timeout: 2000.

It is the single most effective resilience setting in the pool, and the default is set for a world without retrying clients.

Q113. "What does the JDBC driver's prepared-statement cache do for Hibernate, and which Hibernate features defeat it?"

Reveal answer

Strong answer When Hibernate prepares the same SQL text repeatedly, the driver can reuse a server-side prepared statement (PostgreSQL's driver after prepareThreshold executions, five by default; MySQL's with cachePrepStmts=true, prepStmtCacheSize=250, useServerPrepStmts=true), saving the parse and plan step per execution — a few hundred microseconds on a simple query, more on complex ones.

Hibernate helps by generating a fixed statement per entity operation and by padding IN lists (Q84) so query texts repeat.

Features that defeat the cache: @DynamicUpdate and @DynamicInsert, which produce a text per column combination; Specifications and criteria queries that vary structurally per request, or that inline literals instead of binding parameters (Hibernate 6 binds by default; hibernate.criteria.value_handling_mode: INLINE would not); native queries built with string concatenation; and unpadded IN lists from hand-written in (:ids) with varying list sizes, where Hibernate 6's hibernate.query.in_clause_parameter_padding: true restores padding.

On PostgreSQL there is a second-order effect: after five executions the server switches to a generic plan, which can be worse for skewed parameters; plan_cache_mode controls it. The interviewer wants to hear that SQL text stability is a performance property you design for.

Land it Stable SQL text is what lets the driver and the database skip planning — dynamic column lists and unpadded IN lists throw that away.

Likely follow-ups
"Explain the generic-plan switch on PostgreSQL and how you would prove it is hurting a specific query."

For a server-side prepared statement, PostgreSQL plans the first five executions with the actual parameter values, custom plans, and records their average cost.

On the sixth it builds a generic plan that assumes typical selectivity, and if its estimated cost is not worse than the custom plans' average, it uses the generic plan from then on without re-planning.

For a skewed column, the generic plan may pick a sequential scan that was right for the common value and terrible for the rare one.

To prove it: run PREPARE q AS select ...; EXPLAIN (ANALYZE) EXECUTE q(rare_value) six or more times in psql and watch the plan change on the sixth execution, or set auto_explain.log_min_duration and see the slow statement's plan differ from the psql one. Then SET plan_cache_mode = force_custom_plan on that session and re-measure.

"Why is @DynamicUpdate bad for the cache, and when is it still right?"

With @DynamicUpdate, Hibernate generates an UPDATE listing only the columns that changed, so an entity with twenty columns can produce up to a million distinct statement texts, though in practice a few dozen.

Each distinct text is a separate entry in the driver's prepared-statement cache and a separate plan on the server, so most executions miss the cache and are planned fresh, and Hibernate itself cannot pre-generate and reuse the statement.

It also disables JDBC batching of updates in any useful way, because consecutive updates rarely share a text.

It is still right in two cases: a very wide entity, a hundred columns, where updating all of them per change is real bandwidth, and a row where concurrent transactions update disjoint columns, because writing only the changed columns avoids overwriting the other transaction's change when there is no version column, which is a workaround for a missing design.

"How do you see the driver's cache hit rate?"

The PostgreSQL driver does not expose a counter, so I infer it from the server: pg_stat_statements shows plans and calls per query text when pg_stat_statements.track_planning is on; a text with calls far above plans is being reused, a text with plans equal to calls is being re-planned every time. On MySQL, SHOW GLOBAL STATUS LIKE 'Com_stmt_prepare' and Prepared_stmt_count tell the server-side story, and Connector/J's prepStmtCacheSize and prepStmtCacheSqlLimit are the client knobs; a statement longer than prepStmtCacheSqlLimit, 256 characters by default, is never cached, and Hibernate's generated SQL routinely exceeds that, so raising the limit to 2048 is a standard tuning step. A datasource proxy can also count distinct texts per minute, which is the application-side signal.

"Hibernate 6 changed how criteria queries bind values. What was the old behaviour and why did it matter?"

Hibernate 5's criteria implementation inlined literal values from cb.equal(root.get("status"), "OPEN") directly into the SQL text as literals, so every distinct value produced a distinct statement, defeating both caches and, for string values, creating an injection-adjacent path.

Hibernate 6 rewrote the query engine and, by default, binds every literal as a parameter, hibernate.criteria.value_handling_mode: BIND, so the text is stable across values.

The INLINE mode still exists for cases where the planner genuinely needs to see the literal, a partitioning key or a highly skewed column, and I would enable it per query through the criteria API's literal handling rather than globally. Hibernate 7 keeps the bind default.

Knowing this history matters when reading old advice that says criteria queries are bad for plan caches; that was true and is no longer.

Q114 · Design. "Design the observability for a JPA service so that an N+1 or a slow query is caught in CI and diagnosed in production within minutes."

Reveal answer

Strong answer Requirements: regressions in statement count fail the build; production exposes per-endpoint database cost; individual slow statements are attributable to code.

In CI: a datasource proxy (datasource-proxy via the datasource-proxy-spring-boot-starter, or p6spy) wrapping the test datasource, and SQLStatementCountValidator.assertSelectCount(n) assertions in the integration test of every endpoint that touches more than one table; hibernate.query.fail_on_pagination_over_collection_fetch: true and open-in-view: false in the test profile so structural mistakes throw.

In production: Micrometer metrics from Hibernate statistics (Spring Boot auto-registers hibernate.* gauges when statistics are enabled — statements, entity fetches, cache hits) tagged by endpoint through a filter that reads the deltas; Hikari metrics for pending and usage; and OpenTelemetry JDBC instrumentation so every span carries the SQL text and duration, which makes a slow query visible in the trace of the request that ran it.

On the database: pg_stat_statements (or Performance Schema on MySQL) for the top statements by total time, correlated to Hibernate's SQL by the alias pattern; log_min_duration_statement at 200 milliseconds for individual outliers.

SQL comments via hibernate.use_sql_comments: true put the JPQL or a query name in the SQL so a DBA can find the Java origin. Trade-offs: statistics and tracing add a small overhead, so sample traces and keep statistics on.

What I would not do: rely on show-sql in production logs, which is unstructured, unsampled and cannot be attributed.

Land it Count statements in tests, tag them by endpoint in metrics, and put the SQL in the trace — then an N+1 is a failed build and a slow query is a span.

Likely follow-ups
"The requirement changes: you cannot add per-endpoint tags because there are 400 endpoints. What stays observable?"

Attribution moves from metrics to traces, which scale with endpoints for free.

OpenTelemetry's Spring instrumentation already tags the server span with the route template, and the JDBC instrumentation attaches every statement as a child span with the SQL text, so a per-endpoint statement count is the number of child spans, computable in the tracing backend without any per-endpoint code.

Metrics keep the global rates: statements per second, entity fetches per second, pool usage, from Hibernate statistics and Hikari. A single alert on the ratio of entity fetches to queries catches new N+1s globally, and the trace tells you where.

The per-endpoint tags were a convenience; the trace has the information. What I keep as code is the SQL comment with the query origin, because a DBA reading pg_stat_statements has no trace.

"What would you cut under time pressure and what would you refuse to cut?"

I cut the production trace sampling and the SQL comments, which are a day's configuration each and can follow, and I cut the per-endpoint metrics filter. I refuse to cut two things.

The CI statement-count assertions on the ten busiest endpoints, because they are an hour each and catch the class of regression that has caused the worst incidents in this drill.

And pg_stat_statements plus log_min_duration_statement, because they are a single configuration change on the database that gives production diagnosis for every statement forever, and without them a slow query at 3 a.m. has no name.

Everything cut goes on a list, and the list is ordered by which incident each item would shorten.

"How do you correlate a slow statement in pg_stat_statements back to the Java code?"

Three routes. The alias pattern: Hibernate 6 and 7 generate aliases from the entity name, o1_0 for Order, l1_0 for lines, so the table and alias structure identifies the entity graph, and a search for the joined tables in the repository finds the query.

The SQL comment: with hibernate.use_sql_comments: true, named queries and Spring Data methods put a comment such as /* select o from Order o join fetch o.lines */ at the front of the SQL, and pg_stat_statements keeps comments in the text, so the JPQL is right there; a @Query with a @Meta(comment = "orderDetail") annotation puts a chosen name.

And the trace: search the tracing backend for spans with that SQL text and open the parent span, which names the route and the service method. The comment is the cheapest and works for the DBA without access to anything else.

"What do you do about the overhead of tracing every statement?"

Sample, and keep the sampling tail-based if the backend supports it. Head-based sampling at one to ten percent keeps every statement span for the sampled requests, which is enough to diagnose patterns and costs almost nothing.

Tail-based sampling keeps every trace that was slow or errored, which is what you actually want for a slow-query hunt, at the cost of buffering traces in the collector.

The JDBC span itself is cheap, a few microseconds per statement to record the text and timing; the cost is export volume, which sampling controls.

I also cap the SQL text length in the span at a few kilobytes so an IN list of a thousand ids does not bloat the trace. Statistics stay unsampled because they are counters; traces are the expensive layer and are sampled.

Q115. "When would you turn the second-level cache off entirely even though it 'works', and what would you use instead?"

Reveal answer

Strong answer I would turn it off when any of these hold: the cached entities are written by anything other than this application's Hibernate sessions — another service, bulk SQL, migrations — because those writes never invalidate the cache and correctness is gone; the deployment has several nodes and no distributed provider, because staleness is then bounded only by TTL (Q107); the hit rate measured by statistics is below, say, 70 percent, because a miss costs more than no cache (a region lookup, a disassemble on store, and the database anyway); or the cached types are queried more than they are loaded by id, because queries bypass it.

It also has a subtle cost with READ_WRITE: soft locks during writes and a per-entity cache entry that can be larger than the row.

Instead: cache what the application actually reuses — the API response or a computed read model — in Caffeine per pod with a short TTL, or in Redis shared across pods with invalidation from the write path after commit (Q109); and use @Immutable plus READ_ONLY L2 regions only for reference data that is loaded by id from write paths, where the L2 cache is cheap and cannot go stale.

The second-level cache was designed for a single-JVM, ORM-owns-the-database world, and most 2026 services are neither.

Land it Any writer outside Hibernate, more than one node without invalidation, or a low hit rate — each alone is a reason to switch it off and cache the read model instead.

Likely follow-ups
"How would you measure the hit rate and decide, with numbers?"

With statistics on, the region-level counts are getSecondLevelCacheHitCount(), getSecondLevelCacheMissCount() and getSecondLevelCachePutCount(), and per region through getCacheRegionStatistics(name). Hit rate is hits divided by hits plus misses.

But the number that decides is the database work saved: misses times the cost of the load it would have avoided, minus the cost of every put and the memory.

If a region shows 10,000 hits and 8,000 misses per minute, an 55 percent rate, the cache saved 10,000 primary-key lookups, which the database could have served in a few seconds of CPU per minute, while the application spent memory and disassembly on 8,000 puts.

I would run a week with the region on and a week off and compare database CPU and p99 for the endpoints that touch the type. If the difference is within noise, off.

"Is there a case for keeping READ_ONLY regions even on a multi-node deployment?"

Yes, for genuinely immutable reference data that is loaded by id from write paths. Currencies, countries, units of measure, and tax categories are never updated in place; a new one is a new row.

A READ_ONLY region on an @Immutable entity cannot go stale because nothing changes, and it removes a join or a probe from every order write that references a currency. There is no invalidation to coordinate because there is no invalidation.

The only operational rule is that a new row is not visible on a pod until that pod misses on that id, which is immediate, since a new id was never cached.

The moment someone wants to edit a currency's name in place, the type is no longer immutable and it leaves the cache; that is the review question for every entity in the region.

"What are the memory costs of the cache that people miss?"

The disassembled state array per entity is roughly the size of the row's values plus object headers, but it lives in the old generation for the life of the entry, so a region of a million products at 500 bytes each is half a gigabyte of long-lived heap per pod, which raises full-collection pauses.

Collection regions store element id lists per owner, cheap individually but numerous. With READ_WRITE each entry is wrapped in an item with a version and timestamp, and the soft locks add transient entries.

And the provider's own structures, JCache with Ehcache, add per-entry overhead and, if configured off-heap, serialisation on every access. The total is visible in a heap histogram as CacheEntry and Object[] instances.

I size regions explicitly with a maximum entry count rather than unbounded, so the memory is a decision.

"Would you use the second-level cache for a single-node deployment?"

More willingly, because the staleness problem disappears when one JVM owns all writes through Hibernate. It still needs the other conditions: no writers outside Hibernate, loads by id rather than by query, and a hit rate that pays.

For a single-node admin application over a reference-heavy schema, a READ_WRITE cache on the lookup types is a real and cheap win, and I would turn it on with ENABLE_SELECTIVE and a handful of @Cacheable types.

The reason to still be careful is the future: the day the application is scaled to two nodes, every cached type becomes a Q107 incident, and nobody remembers that the cache was the reason it was fast.

So the decision is documented next to the configuration with the conditions that made it safe.

10 · DrillProduction Scenarios, Migrations & Design — Q116–Q150

The last block is the one that separates a senior candidate from a strong mid-level one: incidents told as diagnoses, schema changes told as sequences that survive a rolling deploy, and designs told with requirements, trade-offs and refusals. Several questions reach back to A2, E3 and E8, because that is how a real panel probes — the ORM is never the whole story.

Drill · Production incidents

This group tests diagnosis order under pressure: symptom, evidence, ranked causes, fix, prevention — every time.

Q116 · Scenario. "At 09:00 on Monday the orders service's p99 jumps from 80 ms to 4 seconds. No deploy happened. Hibernate statistics show statements per request unchanged. Where do you look?"

Reveal answer

Strong answer Symptom: latency up with the same statement count, so the ORM is doing the same work and each statement got slower.

Evidence: JDBC time per request from the session metrics log; pg_stat_statements or the slow log for which statement's mean time rose; pg_stat_activity for waits; replica lag; and what else runs at 09:00 Monday.

Ranked causes: one, a plan change — PostgreSQL's autovacuum or a weekend analyze changed statistics, and a query flipped from an index scan to a sequential scan, or the prepared statement switched to a generic plan (Q113) that is wrong for Monday's parameter skew; two, lock waits from a weekend batch job or a report still running — long transactions holding locks or pinning old row versions so tables bloated over the weekend; three, connection saturation from Monday's traffic peak with the same pool size, visible as Hikari pending; four, an index bloated or missing after a weekend data load.

Fix: for a plan flip, EXPLAIN (ANALYZE, BUFFERS) the slow statement with real parameters and fix statistics or add the index; for locks, find and kill the blocking session; for the pool, admission control.

Prevention: query-plan monitoring on the top statements, alerts on transaction age and lock waits, and a Monday-morning load profile in capacity planning. Nothing in Hibernate changed, and the answer should say so early.

Land it Same statements, slower statements — the diagnosis moves from the ORM to the plan, the locks and the pool, in that order.

Likely follow-ups
"You found the plan flip and fixed the statistics. Twenty minutes later p99 is back at 4 seconds. What next?"

Then the plan was a symptom, not the cause, or there were two problems.

I would first check whether the plan actually changed back, since a prepared statement's generic plan is cached per connection and a reanalyze does not replan existing prepared statements until the connections cycle; a pool rotation or DISCARD PLANS on the sessions forces it.

If the plan is good and the query is still slow, look at waits rather than CPU: pg_stat_activity with wait_event shows whether the slow statements are waiting on locks, on I/O, or on nothing.

Lock waits point to the weekend job or a long-running transaction, visible by xact_start age. I/O waits point to cache eviction after a large weekend scan that pushed the working set out of shared buffers, which recovers as the cache warms.

Each of those has a different fix, and the wait event is what separates them.

"How would you tell a lock problem from a plan problem in the first two minutes?"

One query: select pid, state, wait_event_type, wait_event, now() - xact_start as age, left(query, 80) from pg_stat_activity where state <> 'idle' order by age desc.

If many rows show wait_event_type = 'Lock' and one old transaction sits at the top holding them, it is a lock problem, and pg_blocking_pids(pid) names the blocker.

If the rows are active with no wait event and each is a copy of the same statement, they are burning CPU on a bad plan, and EXPLAIN (ANALYZE, BUFFERS) of that statement with real parameters confirms it.

If they show IO waits, it is a cold cache or a storage problem. On MySQL the equivalents are performance_schema.data_lock_waits and SHOW ENGINE INNODB STATUS. The point is that the first two minutes are a query on the database, not a look at the application.

"What would you have wanted in place beforehand so this took five minutes instead of an hour?"

Four things. Plan regression monitoring: a nightly capture of EXPLAIN for the top twenty statements by total time, diffed against the previous night, which would have flagged the plan change before traffic arrived.

An alert on the oldest transaction age and on lock-wait counts, which catches the weekend job holding locks into Monday. Hikari pending and usage on the same dashboard as p99, so pool saturation is a glance.

And auto_explain with a threshold of one second and log_analyze on, sampled, so the plan of the actual slow execution with actual parameters is already in the log when the page fires.

All four are configuration and a small script, and they turn "where do you look" into "read the dashboard".

"Could the ORM have contributed at all, even with the same statement count?"

In two indirect ways worth ruling out. The prepared-statement cache: Hibernate's stable SQL text is exactly what leads to a server-side generic plan after five executions, so the ORM's virtue is the mechanism through which a plan flip reaches every connection.

And bound parameter types: if a mapping change shipped weeks ago made Hibernate bind a column differently, for example an enum as text against a varchar column with a different collation, the planner's choice could be marginal and tipped over by new statistics.

Neither is a Hibernate bug, but both mean the fix might involve a query hint, plan_cache_mode per session through a connection initialisation SQL, or a mapping tweak rather than only a database change.

Saying "nothing in Hibernate changed" is right; saying "Hibernate is irrelevant" is not quite.

Q117 · Scenario. "A deploy adds a @Column(length = 500) to a field that was 255. Startup fails on half the pods with a schema-validation error, and the other half are serving traffic. What happened and what now?"

Reveal answer

Strong answer Symptom: a rolling deploy split between old pods running and new pods crash-looping on ddl-auto: validate. Evidence: the validation message names the column and the expected versus found length.

Cause: the mapping changed but no migration widened the column, and validate compares the declared type; the new pods refuse to start, which is validate doing its job.

The half that "works" is the old version, so the rollout stalled — Kubernetes' readiness gate stopped it, which is the good outcome. What now: do not disable validation to force the deploy.

Roll the deployment back so all pods are the old version, write the migration ALTER TABLE ... ALTER COLUMN note TYPE VARCHAR(500) — on PostgreSQL widening a varchar is a metadata change, instant; on MySQL 8 widening within the same byte-length class is INPLACE and quick, but crossing 255 changes the length prefix and rewrites the table, so schedule it — ship the migration in a release that still maps 255 (old code works with a wider column), then ship the mapping change.

Prevention: a CI step that runs Flyway migrations against a schema snapshot and boots the application with validate, so a mapping without a migration fails the build, not the deploy; and the expand-first rule from the primer for every column change.

Going deeper One precision on the MySQL side that interviewers with database depth will probe.

The InnoDB rule for widening a VARCHAR in place is about the length prefix in bytes, not characters: a column whose maximum byte length is 255 or less stores a one-byte length prefix, and above 255 bytes it needs two, so crossing that boundary requires a table rebuild.

With utf8mb4, each character can take four bytes, so VARCHAR(255) is already 1,020 bytes and already uses the two-byte prefix; widening it to VARCHAR(500) is then an instant, in-place metadata change on MySQL 5.7 and 8.

The rebuild case is a column under 64 characters in utf8mb4, or under 255 in latin1, being widened past the byte boundary.

So before scheduling a rewrite, check the character set and compute the byte lengths; the verification is running the ALTER with ALGORITHM=INPLACE, LOCK=NONE on a copy, which errors immediately if a rebuild would be required.

Land it Validate stopped a bad deploy at the readiness gate — the fix is migration first, mapping second, never validation off.

Likely follow-ups
"What exactly does validate check, and what does it not check?"

It compares each mapped entity against the database metadata obtained through JDBC: that every mapped table exists, that every mapped column exists, and that the column's JDBC type is compatible with the mapped type, including, in Hibernate 6 and 7, the declared length, precision and scale where the dialect reports them.

It does not check indexes, foreign keys, unique constraints, check constraints, defaults, nullability, or sequences' increment values, and it does not notice extra columns or tables that the mapping does not use.

So a missing index or a sequence with the wrong increment passes validation and fails at runtime. Hibernate 7 tightened the type checks, for example between timestamp and timestamptz, which is why upgrades sometimes surface validation errors on schemas that had been "passing" for years.

"The rollback fails because the new pods already wrote data the old code cannot read. Now what?"

That means the deploy was not backward-compatible in data, which for a length change should not happen, since a wider value cannot have been written when the column was still 255.

If it did, because the migration was applied by hand to production while pods were rolling, the old code does not fail to read a longer string; it reads it fine and would only fail on a write that exceeds the old mapping's length, and Hibernate does not validate string length on write.

So the practical answer is that the rollback works, and the check is reading the validation error text again: it is the new pods failing, not the old ones.

The general lesson is the one from Q129: every release must be readable by the previous one, and if a release breaks that, the rollback plan is roll forward, which is why the migration must ship first.

"How does the CI boot-with-validate step work in practice?"

A test in the integration suite, annotated @SpringBootTest with the Testcontainers database and the property spring.jpa.hibernate.ddl-auto=validate, whose only body is an empty test method; the context boot is the assertion.

Flyway runs the full migration set on the empty container first, then Hibernate validates every mapping against it, and any mismatch fails the context with the column name and the expected and found types in the message.

It runs in the same JVM as the other integration tests so the container cost is shared. To make it catch the "mapping changed but the migration widened a different column" case, the check must compare lengths, which Hibernate does for varchar.

It takes about ten seconds in the pipeline and would have failed this pull request before it merged.

"Why is the readiness gate the good outcome, and what would have made it a bad one?"

Because Kubernetes only shifts traffic to a new pod once its readiness probe passes, and a pod crash-looping on validation never becomes ready, so the rolling update pauses with the old pods still serving all traffic and the deployment shows as stalled.

That is a failed deploy with zero user impact. The bad outcomes are two.

If the deployment's maxUnavailable allowed the old pods to be terminated before the new ones were ready, capacity would have dropped; the default of 25 percent unavailable is why half the fleet can be in the failing state while traffic is still served.

And if someone had set ddl-auto: none to get the pods up, the new code would have started writing 500-character values to a 255 column and failed on writes in production instead of on startup in the rollout.

Q118 · Scenario. "Production shows intermittent 'duplicate key value violates unique constraint orders_pkey' on inserts after a failover to a new PostgreSQL primary. Diagnose."

Reveal answer

Strong answer Symptom: primary-key collisions appearing after a failover. Evidence: the colliding ids are recent, and the sequence's current value on the new primary is lower than the maximum id in the table.

Cause: PostgreSQL sequences are not transactional, but their state is written to WAL in batches — a sequence pre-logs 32 values ahead and the standby may lag; more importantly, Hibernate's pooled optimizer hands out blocks of 50 in memory.

After a failover, two things can happen: the new primary's sequence may be behind if the failover lost WAL (asynchronous replication, promotion before the last records applied), so it re-issues values that the old primary already handed to application nodes; and application nodes still hold blocks allocated from the old primary and continue to insert ids the new primary's sequence will later reissue.

Fix: immediately SELECT setval('orders_seq', (SELECT max(id) FROM orders) + 1000) on the new primary for every sequence, so it leaps past everything ever handed out; the retrying inserts then succeed.

Prevention: synchronous replication (synchronous_commit = on with a synchronous standby) so promoted standbys are never behind, a post-failover runbook step that bumps all sequences, and, for systems that failover often, client-generated time-ordered UUIDs that cannot collide by construction.

Application-side, treat the unique violation as retryable with a fresh id block.

Land it Sequences replicate loosely and Hibernate caches blocks — after a failover, bump every sequence past max(id) before you trust an insert.

Likely follow-ups
"Why does the pooled optimizer make this worse than a plain sequence call per row?"

Because it moves id allocation into application memory. With allocationSize = 50, a node calls nextval once and then hands out fifty ids itself. At failover time each node holds a block of up to fifty unused ids that the old primary allocated.

If the new primary's sequence is behind, it will re-issue those same values to other nodes' next nextval calls, and the collisions continue until every node's block is exhausted and the new primary's sequence has passed the old high-water mark, which with many nodes and low traffic can take a while.

With a plain per-row nextval, the exposure would be only the 32 pre-logged values, and only if the WAL was lost. The fix is the same, bump the sequence, but the blocks explain why the errors persist after the failover completes.

"You bumped the sequence and the duplicate key errors continue. What next?"

Two possibilities.

The bump was too small: application nodes hold blocks from before the failover, and their highest cached id is above the bump target; use the maximum id in the table plus the number of nodes times the allocation size, with a safety margin, and bump again.

Or a second sequence is involved: a child table with its own sequence, or a table that does not use the sequence I bumped, and the constraint name in the error says which; bump every sequence in the schema with a loop over pg_sequences, setting each to the max of its owning column plus a margin.

If the errors are on the same table and the bump is verified with select last_value from orders_seq, restart the application pods to discard their cached blocks, which is crude but definitive. Then confirm with the error rate returning to zero.

"How does synchronous replication prevent this, and what does it cost?"

With synchronous_commit = on and a named synchronous standby, a commit on the primary does not return until the standby has written the WAL record to disk, so a promoted standby has every committed transaction, including the sequence state updates that were part of committed WAL.

The sequence can still be slightly ahead of the table's max id because of the 32-value pre-logging, which is harmless; it cannot be behind it.

The cost is commit latency equal to the round trip to the standby, typically one to three milliseconds in a region, and the availability coupling: if the synchronous standby is down, commits block until it returns or the configuration is changed, so a second candidate standby in the list is standard.

For a service where a failover producing duplicate keys is worse than a few milliseconds per commit, which is most, it is the right setting.

"Would UUID v7 have avoided the whole incident, and what does it cost?"

Yes, because a UUID v7 is generated on the application node from a timestamp and random bits; no database state is involved, so no failover can cause two nodes to generate the same id, and batching works since the id is known before the insert.

The costs are a 16-byte key instead of 8 in every index and foreign key, a slightly larger working set, and the loss of a compact human-readable id in logs and support tools.

On PostgreSQL with the native uuid type and time-ordered v7 values, insert locality is nearly as good as a sequence, so the B-tree does not fragment as it did with random v4. Hibernate 7's @UuidGenerator(style = VERSION_7) makes it a one-line mapping.

For a system with frequent failovers or multi-region writes, the trade is clearly worth it; for a single-primary system, sequences with the runbook are fine.

Q119 · Scenario. "A service intermittently returns another customer's order details. The code uses a request-scoped cache of the 'current customer' entity. Explain the class of bug and the fix."

Reveal answer

Strong answer Symptom: cross-request data leakage — the most serious kind of ORM bug.

Evidence: correlate the wrong-customer responses with concurrent requests on the same pod; check whether the "request-scoped" cache is actually a field on a singleton bean, a ThreadLocal not cleared between requests, or a cached entity shared across sessions.

Ranked causes: one, a managed entity from one request's persistence context stored somewhere that outlives it — a static map, a singleton field, a Caffeine cache keyed by something that is not the customer id — and handed to the next request, which then reads (or worse, merges and writes) another customer's data; two, a ThreadLocal on a pooled thread (virtual threads make this worse because there is no reuse but also no clearing discipline); three, the second-level cache with a bad natural id or a composite key whose equals is wrong, collapsing two customers into one cache entry.

Fix: never cache entity instances across requests — cache immutable read models keyed by the customer id and validate the key against the authenticated principal on every read; clear thread locals in a filter's finally block; audit equals/hashCode on every id class.

Prevention: an ArchUnit rule that @Entity types never appear in cache or static fields, and a security test that fires interleaved requests for two customers and checks every response's owner.

Land it An entity belongs to one session and one request; the moment it is shared, it is someone else's data waiting to be served.

Likely follow-ups
"How would you reproduce this in a test so you know the fix works?"

An interleaving test with two authenticated users and real concurrency.

Seed customer A and customer B, then fire two hundred requests as A and two hundred as B against the same running application through a thread pool of twenty, in random order, and assert that every response's customer id matches the caller's principal.

With the singleton-field or thread-local bug, some responses fail within the first few hundred requests, because pooled threads alternate between users. To make it deterministic, add a small delay in the request path under a test flag so the interleaving is guaranteed.

The test lives in the integration suite and runs on every build. It is the same shape as the multi-tenant isolation test from Q80, and it is the only kind of test that catches state leaking between requests.

"Why do virtual threads not fix the ThreadLocal problem?"

They change its shape. A platform-thread pool reuses threads, so a ThreadLocal set during request one and not cleared is visible to request two on the same thread, which is the classic leak.

Virtual threads are created per request and discarded, so an uncleared ThreadLocal dies with the thread and that specific leak disappears. But two new problems appear.

Code that used a ThreadLocal as a per-request cache now allocates it a million times, and anything that inherits thread locals into child threads, an InheritableThreadLocal or Spring's context propagation, copies the previous request's values if the child was created from a pooled executor.

So the discipline is the same: request state lives in a request-scoped bean or a ScopedValue on JDK 25, set and cleared at the boundary, never in a thread's storage by default.

"Where else do entities leak across requests that people do not expect?"

Four places I check in an audit. Spring's @Cacheable on a service method returning an entity, which stores the managed instance in the cache manager and hands the same object to every later caller, now detached and possibly mutated.

Static or singleton collections used as "last seen" or "recent" lists. Event payloads: an ApplicationEvent carrying an entity, consumed asynchronously by a listener on another thread after the transaction closed.

And the second-level cache with a bad @NaturalId or key equality, which is Hibernate itself serving the wrong row.

The rule is the one in the answer: entities do not cross the transaction boundary, and the ArchUnit rule that @Entity types do not appear in fields of singletons, in cache annotations' return types, or in event classes enforces it mechanically.

"What is the incident response beyond the fix, given it is a data leak?"

Treat it as a security incident, not a bug. Contain: deploy the fix or, if the fix is not ready, disable the endpoint.

Scope: from access logs and the leak's mechanism, estimate which requests could have received another customer's data, which for a thread-local bug is bounded by pod, time window and interleaving, and produce a list of affected customers.

Notify: legal and the data-protection officer decide on regulatory notification, which under most regimes has a deadline measured in days, so the scoping must be quick and honest. Record: a post-incident review that names the mechanism, the missing test, and the ArchUnit rule now in place.

Engineers often stop at the fix; the interviewer at a senior level wants to hear that a cross-customer leak has obligations beyond the code.

Q120 · Scenario. "A team upgraded to Spring Boot 4 and their Hibernate-specific @GenericGenerator, jpamodelgen and 'org.hibernate.type.descriptor.sql' logging all stopped working. Prioritise the fixes."

Reveal answer

Strong answer Symptom: three unrelated breakages from one upgrade, all Hibernate 6-to-7 removals. Prioritise by what blocks startup.

First, @GenericGenerator: deprecated in Hibernate 6.5 and removed in 7; replace with the typed alternatives — @UuidGenerator for UUIDs, @SequenceGenerator for sequences, or an @IdGeneratorType meta-annotation wrapping a custom IdentifierGenerator — because without a working generator the entities fail to bootstrap.

Second, the annotation processor: hibernate-jpamodelgen is renamed hibernate-processor; update the build's annotation-processor path or the static metamodel classes (Order_) are not generated and criteria queries and Specifications referencing them fail to compile.

Third, logging: the bind-parameter logger moved to org.hibernate.orm.jdbc.bind in Hibernate 6 — cosmetic, but restore it before debugging anything else.

Also check the temporal validation change (Q38), the removed legacy Session methods (save, update, saveOrUpdate — replace with persist/merge), the getOne/getById removal in Spring Data 4, and that spring-boot-starter-data-jpa is still declared explicitly now that the JPA autoconfiguration lives in its own module.

Prevention: the Spring Boot guidance — go to the latest 3.5, clear every deprecation warning, then move to 4 — and a staging boot with validate.

Land it Fix what stops the bootstrap first — generators, then the processor, then logging — and treat deprecation warnings on 3.5 as the real upgrade checklist.

Likely follow-ups
"What does the @IdGeneratorType replacement for a custom @GenericGenerator look like?"

Two pieces. A generator class implementing org.hibernate.generator.BeforeExecutionGenerator, or the older IdentifierGenerator interface which still works, with a generate(SharedSessionContractImplementor session, Object owner, Object currentValue, EventType eventType) method returning the id. And a meta-annotation: @IdGeneratorType(OrderNumberGenerator.class) @Retention(RUNTIME) @Target({FIELD, METHOD}) public @interface OrderNumber { String prefix() default "ORD"; }.

The entity then declares @Id @OrderNumber(prefix = "EU") private String id;, and the generator receives the annotation instance through a constructor parameter, so configuration is typed rather than a string map. It replaces the @GenericGenerator(strategy = "com.x.OrderNumberGenerator", parameters = ...) form that Hibernate 7 removed.

The compile error on the old annotation is the first thing the upgrade shows, which makes it the first fix.

"Why did Spring Boot 4 split the JPA starter, and what breaks if you miss it?"

Spring Boot 4 reorganised auto-configuration into per-technology modules so that applications only pull in what they use and startup does less classpath scanning.

The JPA auto-configuration lives in its own module now, and spring-boot-starter-data-jpa is what brings it in; a project that previously got JPA transitively through another starter, or that declared spring-boot-starter plus Hibernate directly, boots with no EntityManagerFactory, no transaction manager, and repositories that fail to inject with a "no qualifying bean" error.

The fix is the explicit starter dependency. As of Aug 2026, the Spring Boot 4.0 migration guide lists this under the modularisation changes, and the symptom is distinctive enough that it is a fast fix once you have seen it.

It is a good example of why the upgrade plan starts with a staging boot.

"What is the temporal validation change, and why does it surface on upgrade?"

Hibernate 7 validates that the Java temporal type matches the column's time-zone semantics. Instant and OffsetDateTime map to timestamp with time zone; LocalDateTime maps to timestamp without time zone.

Schemas created by older Hibernate versions often have a plain timestamp column under an Instant field, which Hibernate 6 accepted silently and Hibernate 7's validate rejects with a type mismatch.

The fix is either the migration ALTER COLUMN created_at TYPE timestamptz, which on PostgreSQL rewrites the table unless the session time zone is UTC, in which case it is a metadata change, or an explicit @JdbcTypeCode(SqlTypes.TIMESTAMP) on the field to declare the legacy mapping.

It surfaces on upgrade because it is the validation getting stricter about a mismatch that was always there.

"How would you run this upgrade so that production never sees a broken build?"

In three gates. First, on the current 3.5 line, turn every deprecation warning into an error in the build, -Werror with the deprecation lint, and fix them all, since the Spring team designed the 3.5 deprecations as the 4.0 removal list.

Second, a branch on 4.0 that must pass the full suite on Testcontainers with validate and the statement-count assertions, so behavioural changes in query generation are caught along with the compile errors.

Third, a staging deploy that runs a replayed traffic sample with the observability from Q114 on, comparing statements per request and latency against the 3.5 baseline, because Hibernate major versions change SQL generation in ways that are correct and slower. Only then a canary in production.

The whole thing is a couple of weeks for a mid-sized service and mostly mechanical.

Q121 · Scenario. "A scheduled cleanup job that deletes old sessions with a JPQL 'delete from Session s where s.expiresAt < :now' starts timing out and blocking user logins as the table grows to 50 million rows. Redesign."

Reveal answer

Strong answer Symptom: one bulk DELETE touching millions of rows in one transaction holds row locks and generates WAL for minutes, and logins that insert or update sessions wait behind it. Evidence: transaction age and lock waits during the job; the deleted-row count per run.

Redesign, ranked: one, delete in bounded batches — delete from user_session where id in (select id from user_session where expires_at < :now order by id limit 5000) as a native query in a loop, committing each batch and sleeping briefly, so each transaction is milliseconds and no login waits longer than that; two, better, partition the table by expiry day (declarative partitioning on PostgreSQL) and drop the whole day's partition, which is a metadata operation that touches no rows and no locks that matter; three, move sessions out of the relational database into a store with TTL (Redis), which is what the data wants.

Ensure an index on expires_at or the batch subquery scans. Trade-offs: batches are simple but still generate WAL proportional to rows; partition drops are instant but require the partition key in every query and a migration to convert the table.

What I would not do: raise the statement timeout so the big delete "fits", which just makes the blocking window longer, or run the delete through entity cascades.

Land it Delete in small committed batches today, drop partitions tomorrow, and ask whether the rows belonged in this database at all.

Likely follow-ups
"You switched to batched deletes and logins still stall for a second each run. What next?"

Look at what each batch actually locks and how long it holds it.

A batch of 5,000 with a subquery that scans because the index on expires_at is missing or unused takes seconds, and during that time the rows it will delete are locked; check the plan with EXPLAIN ANALYZE and confirm an index range scan.

If the plan is right, check whether the login path and the delete collide on the same rows: a login that updates the session's last_seen on a row the batch is deleting waits for the batch, so ordering both by id makes waits brief, and deleting only sessions expired for more than an hour keeps the batch away from anything a live user touches.

Then the sleep between batches: fifty milliseconds lets waiting transactions through. If stalls remain, the cause is elsewhere, likely WAL pressure from the batch competing with commits, visible as commit latency.

"How does partition dropping actually work, and what does the JPA mapping have to know?"

The table is declared PARTITION BY RANGE (expires_at) with one partition per day, created ahead of time by a scheduled job or pg_partman. Inserts route to the right partition automatically.

The cleanup becomes ALTER TABLE user_session DETACH PARTITION user_session_2026_08_27 CONCURRENTLY followed by DROP TABLE, which removes millions of rows as a file unlink with no row locks and no WAL per row. JPA sees the parent table and needs no change for inserts and reads.

Two things it must respect: every query that should hit one partition must filter on expires_at, or the planner scans every partition; and the primary key must include the partition column, so the entity's id becomes composite or the uniqueness of the session id is enforced per partition, which for sessions is acceptable.

The migration to a partitioned table is the expensive step: create the new table, dual-write, backfill, swap.

"Why is running the delete through entity cascades the wrong tool here?"

Because it loads every row to delete it. A deleteAll(expired) through the repository selects the expired sessions into the persistence context, and then issues one DELETE per row at flush, batched at best into groups of fifty, after checking cascades on each.

For a million rows that is a million entity instantiations and twenty thousand batched round trips, holding the transaction for minutes with the same lock and WAL problem as the big JPQL delete, plus memory.

Cascades exist for aggregates, where deleting an order must delete its lines and the rule lives in the mapping; a session has no children, and the operation is a set predicate.

The native batched delete expresses exactly that, and the only thing lost, lifecycle callbacks, has nothing useful to do for expired sessions.

"Under time pressure tonight, what is the minimum change that stops the login impact?"

Two lines of change and one index. Replace the JPQL with a native @Modifying query using the limit 5000 subquery form, call it in a loop from a non-transactional method so each call is its own transaction, and stop when the returned count is zero.

Confirm the index on expires_at exists, and if it does not, create it with CONCURRENTLY outside Flyway's transaction before the job runs. Add a Thread.sleep(50) between batches.

That takes an hour, ships tonight, and bounds any login's wait to the duration of one 5,000-row delete, which is milliseconds. The partitioning and the move to Redis go on the roadmap with the deleted-rows-per-night metric as the trigger for when they are worth it.

Q122 · Scenario. "The same JPQL query is fast from psql with the literal values but slow from the application. Statistics show one statement. What is different about the application's execution?"

Reveal answer

Strong answer Symptom: identical SQL, different plans. Evidence: EXPLAIN from psql with literals versus the plan the application actually gets, captured with auto_explain for PostgreSQL or by running EXPLAIN with bound parameters via PREPARE/EXECUTE.

Ranked differences: one, parameter binding — the application binds values, so PostgreSQL may use a generic plan after five executions (Q113) that ignores the skew of the actual value; a status of CANCELLED matching 0.1 percent of rows wants an index scan, while the generic plan assumes average selectivity and sequential-scans; two, type mismatch — Hibernate binds a Java String for an enum as text or a Long for an int column, and an implicit cast prevents index use; or a timestamp bound as timestamptz; three, the application's session has a different search_path, timezone or enable_* settings, or runs on a replica with different statistics; four, an implicit AUTO flush before the query in the application adds time that psql never sees — statistics would show it as flush time.

Fix: for plan skew, plan_cache_mode = force_custom_plan on the session or a query rewrite that gives the planner the literal; for type mismatch, align the mapping (@JdbcTypeCode, native enum mapping); for settings, compare SHOW ALL from both. Prevention: auto_explain sampling on slow statements with bound values logged.

Land it The SQL is the same but the plan is not — bound parameters and bound types are the two things psql with literals cannot reproduce.

Likely follow-ups
"How do you capture the plan the application actually got, with its bound parameters?"

With auto_explain loaded on the PostgreSQL side: auto_explain.log_min_duration = 500ms, auto_explain.log_analyze = on, auto_explain.log_buffers = on, and auto_explain.log_format = json, optionally with auto_explain.sample_rate to limit overhead.

Every execution slower than the threshold logs its actual plan, with the parameter values substituted when log_parameter_max_length allows, so the log shows the plan the application's prepared statement used, including the generic-versus-custom choice.

From the application side, the equivalent is to take the bound values from Hibernate's bind log and run PREPARE plus six EXPLAIN ANALYZE EXECUTE calls in psql, which reproduces the plan-cache behaviour that a single EXPLAIN with literals never does.

The first is passive and continuous; the second is for a specific hunt.

"Give a concrete type-mismatch example and how you fix the mapping."

The classic one is an enum. The column is status varchar(16) with an index, and the entity maps @Enumerated(STRING), which is fine.

But if the column is a PostgreSQL native enum type order_status and Hibernate binds a plain varchar, the predicate becomes status = $1::varchar, the planner cannot use the index on the enum column, and the query is a sequential scan from the application while psql with the literal auto-casts and uses the index.

The fix in Hibernate 6.2 and later is @JdbcTypeCode(SqlTypes.NAMED_ENUM) on the field, which binds with the enum type.

A second example: a Long bound against an integer column forces int4 = int8, which PostgreSQL handles with the index but MySQL sometimes does not; align the Java type to the column. Verification is the plan showing an index scan again.

"The application's statement is the same, the plan is the same, and it is still slower. Now what?"

Then the time is not in the query.

Look at what surrounds it in the application: an AUTO flush before the query that dirty-checks a large persistence context, visible as flush time in Hibernate statistics; a result set of thousands of rows being hydrated, which psql shows as instant because it only prints; or the connection wait before the statement even starts, visible in Hikari's pending metric.

Measure the statement's own time with the session metrics log, which reports JDBC execution nanoseconds per session, and compare that with the wall time the application measured.

If JDBC time matches psql and the wall time does not, the difference is the application's work around the statement, and the profiler from Q98 is the next tool. Statistics showing "one statement" says nothing about what happened before and after it.

"Is plan_cache_mode = force_custom_plan a safe global setting?"

It is safe in the sense that every execution is planned with the actual values, so no query gets a wrong generic plan, but it gives up the planning saving that prepared statements were meant to provide: every execution pays the planner, which for simple statements is under a millisecond and for complex joins can be several.

On a service where most statements are primary-key probes it is a small cost, and I have set it globally on services with skewed data and been happy.

The more surgical option is per-session through Hikari's connection-init-sql for the whole pool, or per-transaction with SET LOCAL plan_cache_mode = force_custom_plan before the specific query that suffers, which is a native statement in the service method.

I would start surgical and go global only if the skew problem is widespread.

Q123 · Scenario. "During a traffic spike, thousands of 'could not serialize access due to concurrent update' errors surface from PostgreSQL through Hibernate. The service runs REPEATABLE READ. What do you do in the next ten minutes and the next week?"

Reveal answer

Strong answer Symptom: PostgreSQL's serialisation failure (SQLSTATE 40001), surfaced by Hibernate as CannotAcquireLockException or a PessimisticLockException wrapper, when a REPEATABLE READ transaction tries to update a row changed since its snapshot (see E8).

It is not a bug but a signal that concurrent writers hit the same rows.

Next ten minutes: confirm the error is retryable and that the service retries it — if it does not, add a retry with jitter at the transaction entry point (Spring Retry on the non-transactional caller) and deploy; identify the hot rows from the error's statement text; if a single hot counter is the cause, temporarily route that operation through an atomic single-statement update that does not need the snapshot check.

Next week: decide per write path whether REPEATABLE READ is needed at all — most single-aggregate writes are correct at READ COMMITTED with @Version, and the isolation level is a per-transaction setting (@Transactional(isolation = ...)) rather than a global one; redesign hot-row updates as additive statements or ledgers (Q64); and add a metric on 40001 counts per statement.

What I would not do: switch the whole service to READ COMMITTED in the ten-minute window without knowing which transactions relied on snapshot semantics.

Land it Serialisation failures are retry signals, not errors — retry now, then match each transaction's isolation to what it actually needs.

Likely follow-ups
"Where exactly does the retry go so that it actually re-runs the transaction?"

Outside the transactional method, on a caller that is not itself transactional.

If @Retryable or a retry template is on the same method as @Transactional, the retry re-enters through the same proxy and, depending on advisor order, may run inside the failed transaction, which is marked rollback-only, so every attempt fails.

The pattern is a thin non-transactional service method that loops with backoff and calls the transactional bean's method through its proxy, so each attempt is a fresh transaction with a fresh snapshot and a fresh persistence context.

The exception to catch is Spring's TransientDataAccessException hierarchy, which the PostgreSQL dialect maps 40001 into, plus OptimisticLockingFailureException. Jitter of tens of milliseconds and a cap of three attempts is enough for hot rows; more attempts under a spike just prolong the storm.

"The retries made it worse: latency doubled and the error count barely moved. Why?"

Because retrying a conflicting transaction against a hot row re-enters the same contention, and with a spike in progress the probability of conflicting again is high, so the retries multiply the load on the row without resolving it.

That is the signature of true contention rather than incidental conflict. In the ten-minute window the fix is to remove the read-modify-write on the hot row, not to retry it: replace the load-then-save with a single atomic UPDATE ... SET count = count + 1, which under READ COMMITTED never conflicts because it does not depend on a snapshot, or serialise the hot operation deliberately with SELECT ... FOR UPDATE so waiters queue instead of failing, or move the counter to a ledger and aggregate later.

Retries are the answer for rare conflicts; for a hot spot they are fuel.

"Why is REPEATABLE READ on PostgreSQL different from MySQL here?"

On PostgreSQL, a REPEATABLE READ transaction that tries to update a row already modified and committed by another transaction since its snapshot began aborts with the serialisation failure, the "first committer wins" rule.

On MySQL InnoDB, REPEATABLE READ does not abort: the update sees and locks the latest committed version of the row, writes over it, and the transaction continues, so lost updates are possible silently unless a version column catches them.

So the same code that throws thousands of errors on PostgreSQL would produce silent overwrites on MySQL. The PostgreSQL behaviour is the safer one; the errors are the database refusing to lose an update.

That difference is why the isolation decision in the next week is engine-specific, and why @Version is the portable answer.

"How do you decide, per transaction, whether it needs REPEATABLE READ?"

Ask whether the transaction reads several rows and its correctness depends on them being from the same moment. A report that sums balances across accounts needs a consistent snapshot, so it needs REPEATABLE READ or a read-only transaction with a snapshot.

A single-aggregate update, load one order, change it, save it, is protected by its version column: if the row changed since the load, the version check fails at commit under any isolation level. So it is correct at READ COMMITTED. Most writes are the second kind.

The audit is a list of transactional methods with a one-line justification per method that stays at REPEATABLE READ, and @Transactional(isolation = Isolation.READ_COMMITTED) or the global default lowered with the exceptions marked. Spring's JpaTransactionManager sets the level per transaction on the connection when specified.

Q124 · Scenario. "An integration test suite with @DataJpaTest passes but production fails on a constraint that H2 never enforced. How do you make the tests honest without making them slow?"

Reveal answer

Strong answer Symptom: a test database with different semantics — H2 in PostgreSQL compatibility mode still differs on check constraints, sequence behaviour, JSON, locking syntax, and type coercion.

Fix: run tests against the real engine with Testcontainers — a PostgreSQL container started once per JVM (a static singleton container, or Spring Boot 3.1+'s @ServiceConnection with a shared container), Flyway migrations applied to it so the schema is the production schema, and ddl-auto: validate so mapping drift fails the suite.

Keep it fast: one container for the whole run, not per class; @DataJpaTest's default transaction-per-test rollback keeps the database clean without truncation; disable @AutoConfigureTestDatabase's embedded replacement with replace = NONE; reuse the Docker image locally with Testcontainers' reuse flag; run migrations once and snapshot with a template database if the suite is huge.

Also remove @Transactional from tests that exercise the service layer's own transaction boundaries (Q15), since a test transaction hides lazy-load and flush behaviour. Typical cost: a few seconds of container start per JVM, then per-test cost identical to H2.

Prevention: no H2 dependency in the project at all, so nobody can write a dishonest test.

Land it Test on the engine you run, with the migrations you ship, in one shared container — the honesty costs seconds, not minutes.

Likely follow-ups
"What does the single shared container setup look like in code?"

An abstract base class or a JUnit extension with a static field: static final PostgreSQLContainer<?> PG = new PostgreSQLContainer<>("postgres:17"), started in a static initialiser so it lives for the JVM, and with Spring Boot 3.1 and later annotated @ServiceConnection so the datasource properties are injected without a @DynamicPropertySource.

Spring's context cache then reuses one application context across test classes with the same configuration, so Flyway runs once. Without @Testcontainers on each class the container is not stopped between classes; Ryuk cleans it at JVM exit.

With testcontainers.reuse.enable=true in ~/.testcontainers.properties and .withReuse(true), a developer's container survives across runs, so local test startup is the same as with H2. The total is thirty lines and it is the same in every project I set up.

"How do you keep the database clean between tests without transaction rollback hiding behaviour?"

For tests that must run without a wrapping test transaction, so that the service's own commits and lazy-loading behaviour are real, clean explicitly after each test. The fast way is a TRUNCATE table1, table2, ... RESTART IDENTITY CASCADE across the application tables in an @AfterEach, which on PostgreSQL is a few milliseconds regardless of row count; Hibernate 7's SchemaManager.truncate() does the same from the mapping.

The alternative is per-test data with unique keys so tests do not interfere and never clean, which is faster but needs discipline.

I use rollback for repository-level tests where the transaction boundary is not what is being tested, and truncation for service and endpoint tests that exercise transactions, and I keep the two kinds in separate packages so the distinction is visible.

"The CI runners cannot run Docker. What then?"

Three fallbacks in order of fidelity. A shared PostgreSQL service provided by the CI system, such as a database service container in GitHub Actions or a sidecar in the pipeline, pointed at through environment variables, with a schema per test run to isolate parallel jobs.

An embedded PostgreSQL binary, the zonky embedded-postgres library, which unpacks a real PostgreSQL server into a temporary directory and starts it in a second or two without Docker; it is the real engine, so it is honest.

And only as a last resort, Testcontainers Cloud or a remote Docker host. What I do not fall back to is H2, because the whole point is engine fidelity, and a pipeline that cannot run the real engine should be fixed rather than accommodated.

"Does @DataJpaTest still make sense once you are on Testcontainers?"

Yes, for repository tests.

It boots a slice with the JPA components only, not the web layer, which is faster than a full @SpringBootTest, and it wraps each test in a rollback transaction and injects a TestEntityManager for seeding and flush() plus clear() so the test reads from the database rather than the persistence context.

The two settings to change are @AutoConfigureTestDatabase(replace = NONE) so it does not swap in an embedded database, and spring.flyway.enabled=true in the test profile so the schema comes from migrations rather than create-drop, which @DataJpaTest defaults to.

With those, a repository test is honest and takes tens of milliseconds. The service-layer tests are the ones that need a full context and no test transaction.

Q125. "What does Hibernate do on a constraint violation at flush, and why can the exception you catch be the wrong one?"

Reveal answer

Strong answer When a statement in the flush fails, Hibernate converts the SQLException through its dialect's exception conversion into ConstraintViolationException (naming the constraint when the driver reports it), marks the session as unusable — the persistence context's state no longer matches the database, so the session must be discarded — and the transaction is marked rollback-only.

Spring's PersistenceExceptionTranslationPostProcessor then maps it to DataIntegrityViolationException. It is the wrong exception in three situations.

First, timing: the flush usually happens at commit inside the @Transactional proxy, after your method returned, so a try/catch in the method sees nothing and the caller sees the translated exception from the proxy — handle it one layer up.

Second, batching: with JDBC batching, the failing statement is inside a batch, and the exception may report the batch rather than the row; the row can be identified only from the constraint name and the batch contents.

Third, wrapping: with REQUIRES_NEW or nested calls, the inner failure is a DataIntegrityViolationException but the outer commit throws UnexpectedRollbackException, and a catch of the inner type at the outer layer misses it.

Design consequence: check uniqueness before inserting when the conflict is a business case ("email already registered") and treat the constraint as the last line of defence, catching it at the boundary where the transaction ends.

Land it The violation arrives at commit, outside your method, possibly from a batch — catch it where the transaction ends, and pre-check what users can plausibly collide on.

Likely follow-ups
"How do you identify which row in a batch failed?"

From the constraint name and the driver's batch exception. PostgreSQL reports the constraint and, in the detail field, the key values, for example Key (email)=(a@x.com) already exists, which Hibernate surfaces through ConstraintViolationException.getConstraintName() and the cause's getServerErrorMessage().getDetail().

The BatchUpdateException also carries the update-count array, and the first entry that is EXECUTE_FAILED is the batch position, which maps to the entity order in the flush.

In practice I log both at the boundary and, for imports, fall back to single-row inserts for the failed batch to isolate the row, the same pattern as the Kafka batch in Q89.

Designing so the failure is understood is easier than parsing it: a pre-check on the natural key when the collision is a business case, and the constraint as the backstop.

"Why does the session have to be discarded? Can you not just rollback and continue?"

Because the persistence context's state and the database's state have diverged in a way Hibernate cannot reconcile.

When the flush fails midway, some statements executed and some did not; the entities that were inserted have ids and are marked persistent in the context, the ones after the failure are still pending, and the database has rolled back all of them.

If the session continued, the next flush would try to update rows that do not exist and skip inserts it believes happened. Hibernate marks the session with an exception state and refuses further work.

Spring handles it by rolling back the transaction and closing the EntityManager; the caller gets a clean session on the next transaction.

The practical rule is that any exception from flush ends the unit of work, and the retry, if any, starts fresh from the ids or DTOs, not from the failed entities.

"How would you make the 'email already registered' case deterministic and user-friendly?"

Two layers. In the transaction: check with a query first, existsByEmail, and return a friendly 409 if it exists; this catches the common case cheaply and without an exception.

Then, because two registrations can race between the check and the insert, keep the unique constraint and force the insert to happen inside the method with flush() right after persist(), so the constraint violation is thrown where the method can catch it.

Catch DataIntegrityViolationException in the non-transactional caller, not inside the transactional method, because the transaction is dead once the flush failed; the caller translates it into the same 409 the pre-check would have returned.

The test seeds an existing email and asserts the 409 twice: once from the pre-check path and once with the pre-check disabled to prove the constraint path works.

"Where does UnexpectedRollbackException come from, exactly, and how do you avoid it?"

From participation. An inner @Transactional(REQUIRED) method joins the outer transaction; when it throws a runtime exception, the proxy marks the shared transaction rollback-only, even if the outer method catches the exception and carries on.

At the outer commit, Spring finds the rollback-only flag, rolls back, and throws UnexpectedRollbackException to say "you tried to commit something already doomed". Three ways to avoid it. Do not catch and continue after a failed inner transactional call in the same transaction; let it propagate.

Make the inner call REQUIRES_NEW when its failure should be independent, accepting that it runs on its own connection. Or set noRollbackFor on the inner method for the exception type that is a business outcome rather than a failure.

The exception's message names the flag, which is the clue that an inner call set it.

Q126 · Scenario. "A background job and a REST endpoint both update the same customer, and support reports that address changes sometimes 'come back' hours later. No optimistic lock errors are logged. What is the mechanism?"

Reveal answer

Strong answer Symptom: a write is reverted long after it was made, with no conflict detected. Evidence: the audit log shows the address updated at 14:00 by the user and reverted at 17:00 by the job; the job's transaction started at 13:00.

Cause, ranked: one, the job holds detached customer entities loaded hours earlier — perhaps in a list it iterates slowly — and calls save() on each at the end, which merges the stale detached state over the current row; with no @Version, nothing detects that the row changed in between, and the 13:00 address wins; two, the job runs one long transaction at REPEATABLE READ on MySQL, where the snapshot from 13:00 is what the job's dirty check compares against and writes back — MySQL does not abort the writer (Q37), so the lost update is silent; three, a JPQL bulk update in the job that sets all columns from stale values.

Fix: add @Version to the customer so the stale merge fails and the job must reload; make the job process each customer in its own short transaction, loading fresh state immediately before changing it; and have the job update only the columns it owns (a targeted @Modifying update) rather than merging whole entities.

Prevention: @Version on every aggregate that more than one writer touches, as a standing rule.

Land it A stale detached entity merged hours later is a time machine — @Version is what stops it from rewriting the present.

Likely follow-ups
"You added @Version and now the job fails nightly with optimistic lock exceptions. Is that success?"

Partly. The exceptions are the lost updates that used to be silent; each one is a customer whose address would have been reverted.

So the detection is a success, and the failures are the job's design flaw made visible: it holds stale entities for hours and writes them late.

The fix is the second half of the answer: restructure the job to process each customer in its own short transaction, loading immediately before changing, so the window between load and save is milliseconds and conflicts become rare.

For the rare remaining conflict, retry that customer once with a fresh load. A job that fails as a whole because one customer conflicted is the wrong granularity; a job that skips and retries per customer is right.

The exception count per night becomes the metric, and it should be near zero once the structure is fixed.

"Why does merge() not detect that the row changed if there is no version column?"

Because merge has nothing to compare against. merge(detached) loads the current row into a managed instance, copies every field from the detached object onto it, and at flush the dirty check compares the managed instance against the snapshot from that load.

The fields that differ from the just-loaded row are written, and the detached object's values always win because they were copied last. The database's intervening change is exactly what gets overwritten.

With @Version, the copy includes the detached object's version, the flush's UPDATE carries where version = ? with the old value, and a zero update count throws. Without a version, JPA has no memory of when the detached state was read.

That is why @Version is not optional on anything that can be detached and merged.

"How would you find the offending code path in a large codebase?"

Search for the pattern rather than the symptom.

Every save() or merge() call whose argument was not loaded in the same transaction is a candidate; concretely, grep for repository save calls in classes annotated @Scheduled or in batch jobs, and for fields or collections that hold entities across loop iterations.

A runtime check helps: a Hibernate Interceptor or PreUpdateEventListener that logs an UPDATE whose entity was loaded more than a few seconds before the flush, using the load timestamp stored in a transient field set in @PostLoad.

Run it in staging against the job and it prints the exact class and the age of the stale entity. Then the audit log's timestamps, the 13:00 load and the 17:00 write, confirm the match.

"Could a JPQL bulk update in the job cause this, and how would it look different?"

Yes, if the job computes new values from data it read hours ago and writes them with update Customer c set c.address = :addr where c.id = :id.

The mechanism is the same staleness, but the signature differs: no entity is merged, so @Version on the entity does not help unless the statement is update versioned, and the audit shows the write coming from a statement rather than a flush.

The fix is to write only the columns the job owns, with a predicate that guards against staleness, for example where c.id = :id and c.updatedAt = :seenAt, and to treat a zero update count as a conflict.

That is optimistic locking by hand for a bulk statement, and it belongs in a comment so the next reader knows why the extra predicate is there.

Q127. "Cross-cutting: a service uses JPA on the primary and reads from a replica for reports. A user saves an order and the confirmation page, reading from the replica, shows it missing. Where does the ORM fit in the fix?"

Reveal answer

Strong answer The symptom is replication lag breaking read-your-own-writes, a distributed-systems problem covered in A2 and E8; the ORM's role is to make the routing explicit and controllable.

The routing usually keys on @Transactional(readOnly = true) through an AbstractRoutingDataSource or the AWS JDBC wrapper (Q16), so the first step is to make sure the confirmation read is not read-only — or is annotated with a custom marker that forces the primary — for a short window after a write.

Options: a per-user "last write timestamp" in the session cookie, with a filter that pins that user's reads to the primary for a few seconds after a write (the routing datasource reads a thread-local set by the filter); or pass the write's commit LSN (pg_current_wal_lsn()) back to the client and, on read, wait until the replica has replayed it — precise but more moving parts; or serve the confirmation from the write path's returned DTO without a second read at all, which is usually the best answer.

What the ORM must not do: mix a replica connection into a transaction that also writes, or let lazy loads inside a "read-only" transaction go to a different connection than the initial query — Hibernate uses one connection per session, so that is safe, but two sessions in one request are not.

Prevention: a rule that the response to a write is built from the write transaction's own state.

Land it readOnly is your routing switch — control it per request after a write, or better, do not re-read what you just wrote.

Likely follow-ups
"Show how the AbstractRoutingDataSource decides, and where it goes wrong with lazy loading."

The routing datasource overrides determineCurrentLookupKey() to return "replica" or "primary", typically from TransactionSynchronizationManager.isCurrentTransactionReadOnly(). The key is evaluated when a connection is borrowed, which with delayed acquisition is at the first statement inside the transaction, and Hibernate holds that one connection for the session's life.

So all statements in a read-only transaction, including lazy loads, go to the replica, and all in a write transaction go to the primary; that part is safe.

It goes wrong when a lazy load happens outside the transaction, with open-in-view on: the session borrows a new connection with no transaction context, the key defaults to whatever the lookup returns for "no transaction", and the lazy-loaded data may come from a different replica or the primary than the original query, giving a mixed-consistency object graph. Another reason for OSIV off.

"What does the LSN-based approach cost, and when is it worth it?"

After the write commits, the service reads pg_current_wal_lsn() on the primary and returns it to the client in a header or cookie.

On a subsequent read, the client sends it back, and the read path checks the replica's pg_last_wal_replay_lsn(); if the replica is behind the token, the service either waits briefly and rechecks or routes that read to the primary.

The costs are one extra statement per write and per read, a token in the client contract, and code on the routing path.

It is worth it when many users need read-your-writes across many endpoints and the primary cannot absorb all post-write reads, which is the case for a large consumer product.

For a service with a handful of write-then-read flows, the "pin the user to primary for five seconds after a write" approach is simpler and good enough.

"Why is 'build the response from the write transaction' the best answer, and when is it not enough?"

Because it removes the second read entirely: the service already has the saved order in the transaction, maps it to the response DTO before commit, and returns it, so there is nothing to be missing. No routing, no lag, no token.

It is not enough in two cases. When the confirmation page needs data the write did not produce, for example a computed delivery estimate from another table updated by a trigger, though that can be read on the primary inside the same transaction.

And when the user navigates away and back, hitting a fresh read endpoint that goes to the replica; that page is the one that needs the short pin or the token.

So the design is: write responses are self-contained, and reads within a short window after a write go to the primary.

"How does the AWS JDBC wrapper's read-write splitting behave with Spring's transactions?"

The wrapper's readWriteSplitting plugin switches the underlying connection to a reader when Connection.setReadOnly(true) is called and back to the writer on setReadOnly(false).

Spring's JpaTransactionManager calls setReadOnly(true) on the connection for a @Transactional(readOnly = true) transaction when the datasource is prepared for it, so the switch happens per transaction with no routing datasource in the application.

The caveats: the switch happens at transaction start, so a write inside a read-only transaction goes to the reader and fails; the wrapper may hold two physical connections per logical one, which changes pool arithmetic; and the reader selection is per connection, so lag differs per pod.

It is less code than routing yourself and the same consistency rules apply. Verify with a test that asserts the write path's inet_server_addr() is the primary.

Drill · Migrations & schema evolution

This group tests whether every schema change you propose survives two versions of the code running at once.

Q128. "Why is ddl-auto=update dangerous in production even though it 'only adds things'? Give three concrete failure modes."

Reveal answer

Strong answer First, it runs on every pod at startup simultaneously during a rolling deploy: three pods each try ALTER TABLE orders ADD COLUMN region, two fail on "column already exists" or, worse, wait on each other's DDL locks, and the deploy is a coin toss.

Second, it takes locks with no plan: adding an index or a NOT NULL column on a large table can rewrite or lock the table for minutes on MySQL versions without instant DDL, with no opportunity to schedule, batch or use CONCURRENTLY — and the outage begins the moment the pod starts.

Third, it is incomplete and irreversible: it never drops or renames, so a renamed field becomes a new column beside an orphaned old one full of data nobody migrates; it never narrows a type; it can create a column with a default that does not match the entity's Java default; and there is no history table, so nobody can say which version of the schema production is at or roll it back.

A fourth: it needs DDL privileges on the application's database user, which is a security finding on its own. validate checks the mapping against the schema and refuses to start on drift, which is exactly what you want; every change is a reviewed migration file.

Land it Update is unscheduled, unreviewed, concurrent DDL with no history — validate plus migrations is the only production setting.

Likely follow-ups
"What about create-drop or update in a staging environment? Is that acceptable?"

Not in staging, because staging exists to rehearse production, and a schema produced by update differs from one produced by migrations in defaults, nullability, index names and column order, so the rehearsal is of the wrong thing.

Staging should run the same migrations, ideally against a restored copy of production's schema.

create-drop is fine for a throwaway local profile and for unit-level tests with @DataJpaTest that do not care about the schema's exact form, and even there I prefer migrations on Testcontainers because the gap between the two shapes is where validation failures hide until deploy.

The rule I use: create-drop only where the database is destroyed at the end of the run, validate everywhere a human might look at the data.

"How does the Hibernate-generated DDL differ from what a DBA would write?"

In the things Hibernate does not know.

It picks types by its dialect defaults, so a String becomes varchar(255) and a BigDecimal becomes numeric(38,2) unless annotated; it names foreign keys and indexes with hashed names like FKa1b2c3 that nobody can read in a lock report; it does not create indexes on foreign-key columns, which on PostgreSQL means every delete of a parent scans the child table; it never partitions, never adds check constraints beyond what @Check declares, never sets fill factors or storage parameters, and does not know which columns are hot.

The generated DDL is a correct sketch of the mapping and a poor production schema. The export from SchemaManager is useful precisely as a diff against the reviewed migrations, not as the migration.

"A small team with one pod says update is fine for them. What is your answer?"

That the first two failure modes are about concurrency and locks, which one pod avoids, but the third is about history, and history is what they will need the day something goes wrong.

With update there is no record of when a column was added, no way to reproduce the schema on a new environment except by booting the old code, and no way to remove or rename anything, so the schema accretes.

The cost of migrations for a small team is one file per change, and Flyway's baseline takes an hour to set up. The moment they add a second pod or a second developer, they inherit the other two problems with no time to fix them.

I would let them keep update for a prototype with no production data, and require migrations from the first real deploy.

"Which one of the failure modes is the hardest to recover from?"

The orphaned column after a rename, because the data is now in two places and nobody knows which is authoritative.

A field renamed from status to state produces a new empty state column while status keeps the old values; the application writes new rows with state and reads nothing from status, so old orders appear to have no status, and the bug is discovered weeks later when a report is wrong.

Recovery is a backfill that must decide, row by row, whether the old or the new column wins, with the write history lost. The lock problem is painful but ends; the concurrent-DDL problem fails loudly.

Silent data divergence is the one that costs a week of forensic work, and it is the strongest argument for validate, which refuses to boot when a mapped column is missing.

Q129 · Design. "Design a zero-downtime rename of orders.status to orders.state across a rolling deploy, with the exact ordering of migrations and code releases."

Reveal answer

Strong answer Requirements: no moment where any running pod version fails to read or write, no full-table lock, and a rollback path at every step. Sequence: Release 1 migration V21__add_state.sql: ALTER TABLE orders ADD COLUMN state VARCHAR(16) NULL — instant.

Release 1 code: the entity maps both columns; writes set both (@PrePersist/@PreUpdate copy status into state, or a database trigger does the same, which is safer because it also covers bulk SQL); reads still use status.

Backfill outside any deploy: UPDATE orders SET state = status WHERE state IS NULL AND id BETWEEN ? AND ? in batches of 5,000 with short sleeps; add an index on state with CREATE INDEX CONCURRENTLY in a migration marked executeInTransaction=false.

Release 2 code: reads switch to state; writes still set both; migration adds NOT NULL — on PostgreSQL via a CHECK (state IS NOT NULL) NOT VALID then VALIDATE CONSTRAINT, then SET NOT NULL, which avoids the full-table lock.

Release 3 code: writes set only state; the trigger is dropped; the entity no longer maps status. Release 4 migration, one release later: DROP COLUMN status.

Trade-offs: four releases for a rename, and duplicated writes for a few days; each release is independently reversible because the previous code still finds its columns.

What I would not do: RENAME COLUMN in one migration, which breaks every old pod instantly, or a view aliasing the old name, which Hibernate cannot write through cleanly.

Land it Add, dual-write, backfill, switch reads, stop writing old, drop — six steps, each surviving a rollback of the step before.

Likely follow-ups
"The requirement changes: the column also changes type, from a varchar status to a smallint state code. What changes in the sequence?"

The dual-write step can no longer be a simple copy, so the mapping between values becomes explicit code.

The trigger or the @PrePersist hook translates 'SHIPPED' to 3 through a lookup table, and the backfill uses the same table in SQL: UPDATE orders SET state = m.code FROM status_map m WHERE m.name = orders.status AND orders.state IS NULL.

The entity maps the new field as a @Converter-backed enum or @Enumerated(ORDINAL) with an explicit ordinal order that must never change, which I would document next to the enum.

The reverse mapping must also exist during the dual-write window in case of rollback, so old pods find valid status strings for rows written by new pods; the trigger handles both directions.

Everything else in the sequence stays, with an extra release of soak time because the translation is where bugs hide.

"Under time pressure, can you collapse the six steps, and which collapse is safe?"

Two collapses are safe. Release 1 and the backfill can be one release if the trigger does the dual-write from the moment the column exists, since the trigger also covers the backfill's window and the backfill can run while Release 1 is live.

And Release 3 and the NOT NULL constraint can be one release, since by then every row has a value. That gives three releases plus the final drop.

The collapse that is not safe is switching reads and stopping writes to the old column in the same release, because a rollback of that release brings back pods that read status, and rows written during the release have no status.

The rule for any collapse is to ask whether the previous release's code still works on rows written by this one; if yes, collapse.

"Why is a database trigger safer than @PrePersist for the dual-write?"

Because the trigger runs for every writer, and @PrePersist runs only for entity writes through Hibernate.

A JPQL bulk update, a native statement, a migration backfill, a support engineer's manual fix, or another service sharing the table would all write status without state, and those rows would break the switch-reads release.

The trigger BEFORE INSERT OR UPDATE ON orders FOR EACH ROW sets NEW.state := NEW.status when state is null, and the reverse when status is null, in a few lines.

Its costs are a small per-write overhead and being invisible in the Java code, which is why it is created and dropped by named migrations with a comment that references the rename ticket. The entity-side hook is fine as an addition, not as the only mechanism.

"What does the NOT VALID plus VALIDATE dance actually avoid on PostgreSQL?"

ALTER TABLE orders ALTER COLUMN state SET NOT NULL on its own takes an ACCESS EXCLUSIVE lock and scans the whole table to verify no nulls, blocking every read and write for the scan's duration, which on a large table is minutes.

Adding CHECK (state IS NOT NULL) NOT VALID takes a brief lock and does not scan; it only enforces the rule for new writes. VALIDATE CONSTRAINT then scans the table holding only a SHARE UPDATE EXCLUSIVE lock, which allows reads and writes to continue.

Since PostgreSQL 12, once a valid check constraint proving non-nullness exists, SET NOT NULL skips the scan and is instant, and the check can be dropped afterwards. Three statements, no user-visible lock, and the migration comments explain why it is not one line.

Q130 · Scenario. "A Flyway migration adding a NOT NULL column with a default to a 300-million-row MySQL 5.7 table locked the table for 40 minutes. What should have happened, and how do you handle the next one?"

Reveal answer

Strong answer Symptom: a DDL that rewrote the table.

Cause: MySQL 5.7's ADD COLUMN is an INPLACE operation that still rebuilds the table's data files for most column additions, holding a metadata lock that blocks writes and, once writers queue, blocks reads behind them; 300 million rows at a few hundred thousand per second is tens of minutes.

What should have happened: on MySQL 8.0.12 and later, ALTER TABLE ... ADD COLUMN ... , ALGORITHM=INSTANT is a metadata-only change for a column added at the end; on PostgreSQL 11 and later, a NOT NULL column with a constant default is instant too.

On 5.7 the right tool was an online schema change tool — gh-ost or pt-online-schema-change — which creates a shadow table, copies rows in chunks while capturing changes from the binlog or triggers, and swaps the tables in a sub-second rename.

Next one: upgrade to MySQL 8 if at all possible (5.7 is past end of life since October 2023); until then, run every non-trivial DDL through gh-ost from a runbook, outside Flyway's transaction, with the Flyway migration reduced to a marker or a -- gh-ost applied note so history stays consistent; test every DDL on a production-sized copy and record the lock duration before approving it.

Prevention: a rule that any migration touching a table over ten million rows needs a written plan with expected lock time.

Land it On old MySQL, DDL is a table rewrite unless a tool does it in chunks — and the honest fix is being on an engine where adding a column is instant.

Likely follow-ups
"Explain how gh-ost keeps the shadow table in sync without triggers."

gh-ost creates a copy of the table's structure with the change applied, then does two things concurrently. It copies existing rows from the original to the shadow in chunks by primary-key range, throttling itself on replication lag and load.

And it connects to the MySQL binary log as if it were a replica, reads every row change on the original table as it happens, and applies the equivalent change to the shadow table, so the shadow converges on the original.

When the copy finishes and the binlog applier is caught up, it performs an atomic cut-over: a brief lock, a rename of original to old and shadow to original, done in under a second.

Because there are no triggers on the original, the production write path pays nothing during the migration, which is the difference from pt-online-schema-change. The requirements are row-based binlog and a primary key.

"How do you keep Flyway's history honest when the real DDL ran through gh-ost?"

The migration file still exists and still has a version, but its body is the marker rather than the DDL: a comment describing the gh-ost command and a no-op statement, or, better, a statement that asserts the change is present, for example a SELECT against information_schema.columns wrapped in a procedure that raises an error if the column is missing. Flyway records the version and checksum, so every environment's history shows the change at the same point, and an environment where the DDL was not run fails the assertion at deploy rather than silently drifting. In development and CI, where tables are small, a Java-based migration can run the plain ALTER TABLE directly when it detects the table is under a size threshold, which keeps the fast path automatic and the production path manual.

"On MySQL 8 with ALGORITHM=INSTANT, what still forces a rebuild?"

Instant DDL covers adding a column, and since 8.0.29 adding it at any position rather than only at the end, dropping a column, renaming a column, and changing a default.

It does not cover changing a column's type, adding or dropping an index, changing the character set, or adding a primary key; those are INPLACE at best, which still rebuilds the data files, or COPY.

There is also a counter: each table permits a limited number of instant column additions before a rebuild is required, the row versions limit of 64 since 8.0.29, which a table that has been altered instantly many times will hit unexpectedly.

The way to know is to run the statement with ALGORITHM=INSTANT explicitly; MySQL refuses immediately with an error if it cannot, rather than falling back silently, so the migration never surprises you.

"What does the written plan for a large-table DDL contain?"

Five things, on one page. The exact statement, with the algorithm and lock clauses. The engine's expected behaviour for that statement and version, with the documentation link, so a reviewer can check the claim.

The measured duration and lock class on a production-sized copy, from an actual run, not an estimate. The rollback: for an added column, dropping it; for a gh-ost swap, the old table is kept for a day and the rename can be reversed.

And the schedule and monitoring: when it runs, who watches replication lag and the error rate, and the abort criteria.

It sounds heavy, but it takes an hour for a change that could take a table down for forty minutes, and after the first few it becomes a template that most changes fill in trivially.

Q131. "How do Flyway checksums, repeatable migrations, and 'out of order' interact with a team of ten developers merging migrations on feature branches?"

Reveal answer

Strong answer Flyway records each applied versioned migration with a checksum of its content; on startup it verifies every recorded migration's checksum against the file in the classpath and fails on mismatch, so an applied migration can never be edited — a fix is a new migration.

Repeatable migrations (R__) have no version; they run after all versioned ones whenever their checksum changes, which is right for views, functions and reference-data upserts written idempotently.

With ten developers, two branches will both create V42__: the second to merge gets a version conflict at startup if it ends up lower than an already-applied one, because Flyway by default refuses to apply a migration with a version below the current high-water mark.

Options: timestamp-based versions (V20260828_1430__add_state.sql), which almost never collide and sort by creation time; outOfOrder=true, which lets a lower version apply later — acceptable in development, risky in production because the migration was never tested in the order it now runs; and a CI check that fails a merge if the branch's migration version is not greater than main's latest.

Also validateOnMigrate and ignoreMigrationPatterns for hotfix branches applied ahead of main. The discipline that matters most: migrations are append-only and forward-only, and a bad one is fixed by another migration, never by editing history.

Land it Timestamps for versions, repeatables for idempotent objects, and never outOfOrder in production — history is append-only.

Likely follow-ups
"A migration was applied in production and then found to be wrong. Walk through the options."

Never edit the applied file, because the checksum check will fail on every environment that already ran it.

Write a new migration that corrects the schema: a wrong column type becomes an ALTER, a bad index becomes a drop and a correct create, and a data mistake becomes an UPDATE with a predicate that targets only the affected rows.

If the wrong migration failed partway on a database that does not support transactional DDL, MySQL, then the history row is marked failed; fix the schema by hand to the pre-migration state or the post-migration state, then run flyway repair to remove the failed row or align the checksum, and re-run.

The only case for editing is when a migration has never been applied anywhere but a developer's machine, and then the developer cleans their own database. Documenting which of these happened is part of the fix.

"What does the CI check for migration ordering look like?"

A small script in the pipeline that lists the migration files on the branch, extracts the versions, and compares the highest version on main against every new file's version; any new file with a version at or below main's highest fails the check with a message telling the developer to renumber.

With timestamp versions the failure is rare and the fix is regenerating the timestamp.

A second check runs Flyway's validate against a database migrated from main with the branch's files added, which catches a duplicate version between two branches merged in sequence and a modified applied file. Both take seconds.

The alternative, discovering the ordering problem at deploy when Flyway refuses to start, costs a rollback and a rushed renumbering.

"When is outOfOrder acceptable, and what safeguards would you add if you used it?"

It is acceptable in development databases where developers switch branches and migrations arrive in arbitrary order, so that nobody has to rebuild their database daily.

In production I would use it only for a hotfix branch whose migration must ship before a higher-versioned migration already in production, and only with safeguards: the hotfix migration is proven independent of the later ones by running it after them on a copy of production, a note in the file names the later versions it was tested against, and outOfOrder is enabled for that single deploy and turned off afterwards.

The safer alternative for hotfixes is a version higher than everything applied, since Flyway does not care that the number is out of sequence with the branch's intent. Timestamps make this the natural default.

"Repeatable migrations run whenever their checksum changes. What is the trap?"

Idempotence and ordering. A repeatable migration must be safe to run any number of times, so it uses CREATE OR REPLACE VIEW, INSERT ... ON CONFLICT DO UPDATE for reference data, and never a plain INSERT or ALTER.

It runs after all pending versioned migrations in every deploy where its content changed, so a view definition that references a column added by a versioned migration in the same release works, but a view that references a column dropped by a versioned migration fails until the repeatable is updated in the same commit.

And repeatables run in alphabetical order of their description, so dependencies between views are ordered by naming them R__010_base_view.sql and R__020_derived_view.sql. Forgetting any of these gives a deploy that fails only when the repeatable's checksum happens to change.

Q132 · Design. "Design the migration from a single orders table to a separately deployed 'fulfilment' service owning shipments, without a big-bang cutover."

Reveal answer

Strong answer Requirements: no shared database between services at the end state, no downtime, the ability to abort at any phase, and correctness of shipment data throughout. Phases.

One, carve the boundary in code first: a Shipment aggregate in the monolith with its own repository and no JPA relationship to Order — only an orderId value — so the ORM stops joining across what will become a service boundary; this alone finds every hidden coupling.

Two, dual-write behind a feature flag: the monolith writes shipments to its table and publishes shipment events from an outbox; the new fulfilment service consumes them into its own database with Flyway-managed schema.

Three, backfill history through a one-off batch export (keyset chunks, Q100) with reconciliation counts by day. Four, shadow reads: the monolith serves shipment reads from its table while comparing against the fulfilment service's API and logging mismatches, until the mismatch rate is zero for a week.

Five, switch reads to the service, then writes (the monolith calls the service's API, or the service consumes order events directly), then stop writing the old table and drop it a release later.

Trade-offs: the dual-write window needs the outbox for consistency, and the reconciliation is real work; the reward is a reversible path at every step.

What I would not do: a @ManyToOne from Order to Shipment across two schemas "temporarily", or a shared table with two writers (Q72). E7 owns the service-decomposition side.

Land it Break the JPA relationship first, dual-write through an outbox, shadow-read until the diff is zero, then move reads, writes, and finally the table.

Likely follow-ups
"The requirement changes: the fulfilment team wants to keep using the same PostgreSQL instance for a year. Does the plan change?"

The instance can be shared; the schema and the tables cannot. The fulfilment service gets its own schema, fulfilment, with its own database role that has no privileges on the orders schema, its own Flyway history table, and its own connection pool.

That preserves every step of the plan, since the boundary is enforced by grants rather than by network distance, and it avoids the operational cost of a second instance for a year.

What must be refused is any foreign key or query across schemas, which the role separation makes impossible, and any shared sequence. The physical split later is then a dump and restore of one schema plus a connection-string change, which is a weekend.

The plan changes only in phase two, where the new service's database is a schema on the same box.

"Under time pressure, which phase do you shorten and which do you not?"

I shorten the shadow-read phase from a week of zero mismatches to a few days with a mismatch rate under a threshold, accepting that rare edge cases will surface after the switch and must be reconciled by hand.

I shorten the backfill by exporting with COPY rather than a JPA batch.

I do not shorten phase one, the code boundary, because that is where the hidden couplings live and every skipped one becomes a production bug in phase five; and I do not skip the outbox in the dual-write phase, because dual-writing without it means the two stores diverge on every failed publish, and the reconciliation that would take a day becomes an unbounded debt. The order of phases stays; only their durations move.

"How do you make the shadow-read comparison cheap enough to run on every request?"

Sample and go asynchronous.

The monolith serves the read from its own table as before, then, for a configurable fraction of requests, publishes the request and its response to a comparison worker, which calls the fulfilment service, normalises both responses by sorting keys and dropping timestamps, and records match or mismatch with the diff.

The user path pays a queue put; the comparison happens off the request thread. A one percent sample at a thousand requests per second is ten comparisons per second, which is trivial, and it still finds a mismatch class within minutes.

The mismatch log is grouped by field, and each group becomes a ticket. The sample rate goes to a hundred percent for a day before the switch, with the worker scaled up, as the final proof.

"What happens to the JPA relationship removal in phase one when other code depends on order.getShipments()?"

Each dependent becomes an explicit query, which is the point. The accessor is replaced by a ShipmentRepository.findByOrderId(orderId) call in the service that needs the shipments, or by a ShipmentSummary projection joined in the read query.

The compile errors from removing the accessor are the inventory of couplings, and I would count them before starting, since forty call sites is a sprint and four hundred is a project.

The trade-off is that some pages now run two queries instead of one join fetch, which is the honest cost of a boundary; those pages get a cached read model if it matters.

Cascades from order to shipment disappear, so deleting an order no longer deletes shipments, which is correct, since shipments will belong to another service.

Q133 · Scenario. "A migration adds an index CONCURRENTLY on PostgreSQL and Flyway fails with 'CREATE INDEX CONCURRENTLY cannot run inside a transaction block', leaving an INVALID index behind. Fix and prevent."

Reveal answer

Strong answer Symptom: Flyway wraps each migration in a transaction by default, and PostgreSQL forbids concurrent index builds inside one; the failed build leaves an index marked INVALID in pg_index, which the planner ignores but which is still maintained on every write — pure cost.

Fix: drop the invalid index (DROP INDEX CONCURRENTLY ix_name), then re-run the migration with the transaction disabled — a sidecar file V23__add_index.sql.conf containing executeInTransaction=false, or the -- flyway:executeInTransaction=false script directive in recent Flyway versions — and mark the failed history row resolved with flyway repair so the checksum and state are consistent.

Because a non-transactional migration cannot be rolled back atomically, keep it to the single index statement and make it idempotent with CREATE INDEX CONCURRENTLY IF NOT EXISTS.

Prevention: a CI lint that any migration containing CONCURRENTLY has the non-transactional marker; a post-migration check query for indisvalid = false as part of the deploy; and for MySQL, the equivalent is ALGORITHM=INPLACE, LOCK=NONE, which does run in the ordinary migration.

Hibernate is not involved — validate does not check indexes — but the @Index on the entity should match so schema generation for tests produces the same index.

Land it Concurrent index builds need their own non-transactional migration — and an INVALID index costs writes until you drop it.

Likely follow-ups
"Why is an INVALID index still maintained on writes, and how do you find them all?"

Because from the storage engine's point of view the index exists and must stay consistent for the case where the build is retried or completed; PostgreSQL updates its entries on every insert, update and delete of the table as it does for any index, while the planner refuses to use it for reads because it may be incomplete.

So it is pure overhead: write amplification and disk with no read benefit. Finding them is one query: select indexrelid::regclass, indrelid::regclass from pg_index where not indisvalid.

I run that query as a post-deploy check and as a weekly report, because concurrent builds also fail when cancelled by a statement timeout or a deadlock, not only through Flyway. Each hit is dropped and rebuilt.

"Why not use REINDEX INDEX CONCURRENTLY instead of drop and recreate?"

On PostgreSQL 12 and later that works and is often better, because it builds a fresh copy alongside and swaps, keeping the index name and any dependent constraint.

On an INVALID index from a failed build, though, REINDEX CONCURRENTLY can itself leave a second invalid index with a _ccnew suffix if it fails, so the cleanup query above must be re-run afterwards.

For a plain index with no constraint depending on it, drop and create is simpler to reason about and produces no suffix artefacts.

For an index backing a unique constraint or a primary key, reindex is the only concurrent option, since the constraint cannot be dropped without a lock. Both are non-transactional and need the same Flyway marker.

"What else in a migration must run outside a transaction, and how do you keep the list from growing silently?"

On PostgreSQL: CREATE INDEX CONCURRENTLY and DROP INDEX CONCURRENTLY, ALTER TYPE ... ADD VALUE for enums before version 12, VACUUM, CREATE DATABASE and ALTER SYSTEM, and DETACH PARTITION CONCURRENTLY.

On MySQL, DDL is never transactional anyway, so the concern is the opposite: a migration mixing DDL and DML cannot be rolled back atomically.

The list stays in the migration linter: a script in CI that scans new migration files for those keywords and fails unless the file carries executeInTransaction=false, and conversely fails a non-transactional file that contains more than one statement, since a multi-statement file with no transaction can half-apply.

Two regular expressions and a comment explaining each, reviewed when the PostgreSQL version changes.

"How do you make the migration idempotent so a retry after a partial failure is safe?"

With CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_orders_customer ON orders (customer_id), a retry after success is a no-op. But IF NOT EXISTS sees an INVALID index as existing, so a retry after a failed build does nothing and leaves the invalid index in place.

The idempotent form therefore needs two statements or a guard: DROP INDEX CONCURRENTLY IF EXISTS ix_orders_customer followed by the create, in a non-transactional migration, which is safe because the drop of a valid index is only wasteful, not harmful, if the migration reruns.

A stricter alternative is a Java migration that queries pg_index and drops only if invalid. Whichever, the post-migration validity check remains the real guarantee.

Q134 · Design. "Design how schema and entity changes flow through CI so a mapping change can never reach production without its migration."

Reveal answer

Strong answer Requirements: mapping and migration verified together on the real engine before merge; migration safety reviewed with lock-time evidence; production schema state observable.

Pipeline: one, a Testcontainers PostgreSQL job that applies all Flyway migrations from scratch, then boots the application context with ddl-auto: validate — a mapping without a migration, or a migration that does not match the mapping, fails here; two, a second job that restores last night's anonymised production schema snapshot (structure plus row counts, or a sampled copy) and applies only the branch's new migrations, timing each and failing on any statement over a threshold or any full-table lock detected through pg_locks — this catches the "instant on an empty table, 40 minutes in prod" class; three, a diff check comparing Hibernate's generated schema (jakarta.persistence.schema-generation.scripts.action=create into a file) against the migrated schema, as a review artefact showing exactly what the migrations changed; four, an ArchUnit or lint rule that @Entity file changes require a migration file in the same PR unless labelled "mapping-only"; five, at deploy, Flyway runs as a separate job before the rolling update (a Kubernetes job or an init step on one pod with a lock), never concurrently on every pod, and a post-migration query records the schema version in a dashboard.

Trade-offs: the production-snapshot job is the slow and valuable one; run it only when migrations change. What I would not do: run Flyway inside every pod's startup in production, which reintroduces the concurrent-DDL problem of ddl-auto=update.

Land it Validate the mapping against migrated schema in CI, time migrations on a production-shaped copy, and run Flyway once per deploy — not once per pod.

Likely follow-ups
"The requirement changes: the team cannot get an anonymised production snapshot for compliance reasons. What replaces the timing job?"

A synthetic production-shaped database.

The schema comes from migrations; the volume comes from a generator that fills the large tables to production row counts with plausible distributions, which can be a few hundred lines of SQL using generate_series and random functions, run once and stored as a database template or a disk snapshot that the job restores in seconds.

Row counts and index sizes are what determine lock duration and rebuild time, not the actual values, so the timing results are representative.

The generator needs updating when a new large table appears, so the lint rule that requires a migration file per entity change also requires the generator to know about any new table over a threshold.

It is more work than a snapshot and it is honest about what it measures.

"Under time pressure, which of the five pipeline parts ships first?"

The first and the fifth. The Testcontainers boot with validate is an afternoon and catches the whole class of "mapping without migration"; it goes in on day one.

Running Flyway once per deploy as a separate job rather than on every pod is a deployment-manifest change and removes the concurrent-DDL risk, which is the risk with the worst blast radius; it goes in the same week.

The DDL diff artefact and the entity-change lint are conveniences that follow.

The production-shaped timing job is the most valuable per incident prevented but the most work, so it ships when the first large-table migration is on the horizon, and not before, because until then it measures nothing that matters.

"How does the once-per-deploy Flyway job coordinate with pods that start before it finishes?"

Ordering in the deployment. In Kubernetes the migration runs as a Job that the pipeline waits on before applying the new Deployment, so no new pod starts before the schema is ready, and old pods keep running on the old schema because every migration is expand-first.

If a pipeline cannot enforce ordering, an init container on each pod runs flyway validate, not migrate, and blocks until the schema version matches what the code expects, so pods wait rather than race.

Flyway also takes an advisory lock on the history table, so if two migrators did run concurrently, one would wait rather than collide; that is a backstop, not the design.

The failure to plan for is a migration job that fails halfway on MySQL, which needs the repair step in the runbook.

"What does the DDL diff artefact show a reviewer that reading the migration does not?"

The gap between what the mapping wants and what the migration provides.

Hibernate's generated create script from jakarta.persistence.schema-generation.scripts.action=create lists every table, column, type, length and foreign key implied by the entities; diffing it against the migrated schema, dumped with pg_dump --schema-only, shows columns the mapping declares that the migration did not add, types that differ in precision, and nullable-versus-not-null differences that validate does not check.

A reviewer sees, for example, that the entity says numeric(19,4) and the migration wrote numeric(19,2), which validation passes and which loses two decimal places in production.

The diff is noisy at first, mostly index and constraint names, so it is filtered to columns and types, and a clean diff is the goal.

Q135. "What does Jakarta Persistence 3.2's SchemaManager give you that ddl-auto did not, and how would you use it responsibly?"

Reveal answer

Strong answer EntityManagerFactory.getSchemaManager() exposes schema operations as an API rather than a startup property: create(boolean createSchemas), drop(boolean dropSchemas), validate(), and truncate(), plus Hibernate's extensions for exporting the DDL to a script.

The difference from ddl-auto is control over when and where: instead of a static property that fires on every startup of every pod, code decides — a test fixture can call truncate() between test classes (faster than dropping and recreating), a developer tool can export the generated DDL for comparison against the migrations (Q134), and a diagnostic endpoint can run validate() on demand and report drift without restarting.

Responsible use: never call create, drop or truncate in production code paths — wrap them behind a test-only profile and a guard that refuses unless the datasource URL matches a test pattern; use validate() at startup exactly as before through the property; use the export to review what Hibernate would generate, then write the migration by hand with the locking and phasing the primer describes.

It is a better tool for the same two legitimate jobs — test schemas and drift detection — and it does not change the rule that production schema is owned by migrations.

Land it SchemaManager makes schema operations explicit calls instead of startup magic — use it for tests and drift checks, never as a deployment mechanism.

Likely follow-ups
"What does truncate() do that a hand-written TRUNCATE does not, and what is its trap?"

It derives the table list from the mapping, so a new entity's table is included automatically, and it orders or cascades the truncation to respect foreign keys, which a hand-written list must be updated to do.

Hibernate's implementation disables or works around constraints where the dialect requires it and, on PostgreSQL, issues one TRUNCATE ... CASCADE across the mapped tables.

The trap is that it truncates only mapped tables: Flyway's history table, an outbox table read by another component, or a table used by a native query with no entity are untouched, and sequences are not reset unless the dialect's statement includes RESTART IDENTITY, so ids continue across tests, which is fine but surprising.

In tests I call it between classes, not between methods, and rely on rollback within a class.

"Is a drift-detection endpoint that calls validate() safe to expose, and what does it return?"

Safe if it is on the management port behind authentication, since it reads catalog metadata and touches no data. validate() throws a SchemaManagementException naming the first mismatch, so the endpoint catches it and returns the message, or "ok".

It is useful after a manual database change, after a failover to a replica that was promoted, or when someone suspects an environment was migrated by hand, because it answers "does this database match this build" without a restart.

It costs a metadata query per mapped table, tens of milliseconds. What it does not do is validate indexes or constraints, so it complements the pg_index check from Q133 rather than replacing it.

I have it as a health indicator that flips to degraded on drift, which pages before users notice.

"How would you guard the create and drop calls against accidental production use?"

Three guards, any one of which alone would be a mistake. The methods are called only from a class in the test source set, so production code has no path to them.

The class checks the datasource URL against a pattern, refusing unless it contains testcontainers or localhost, and throws otherwise.

And the production database role lacks DDL privileges, so even a call that slipped through would fail at the database with a permission error rather than dropping tables.

The third guard is the one that holds when the first two are bypassed by someone copying the test helper into a debug endpoint, which has happened in real codebases.

The principle is that a destructive capability is gated by something that does not live in the same code as the capability.

"How does SchemaManager relate to the older hibernate.hbm2ddl and the Jakarta schema-generation properties?"

All three drive the same internal tooling, Hibernate's SchemaCreator, SchemaDropper and SchemaValidator. The hibernate.hbm2ddl.auto property and Spring's ddl-auto alias trigger them at SessionFactory startup. The Jakarta properties, jakarta.persistence.schema-generation.database.action and the scripts.action variants, do the same in a standard way and add script export.

SchemaManager, standardised in Jakarta Persistence 3.2 and available as of Hibernate 6.5 and 7, exposes the same operations as methods on a running factory, so they can be invoked at a chosen moment with the live mapping.

Nothing about the generated DDL changed; the change is who decides when it runs. For production, the answer is still that none of them run, and migrations own the schema.

Q136 · Scenario. "You inherit a service with 400 entities, ddl-auto=update in production, and no migrations. Plan the first month."

Reveal answer

Strong answer Week one, capture reality: dump the production schema (pg_dump --schema-only), commit it as V1__baseline.sql, configure Flyway with baselineOnMigrate=true and baselineVersion=1 so it marks production as at version 1 without running anything, and switch ddl-auto to validate in a staging environment restored from the dump.

Expect validation failures — that is the drift list: columns Hibernate thinks exist, types that differ, the orphaned columns update left behind.

Week two, reconcile: for each drift item, decide whether the mapping or the schema is right, write migrations for the schema fixes, correct mappings for the rest, until staging boots clean on validate; add Testcontainers with migrations to CI (Q134).

Week three, ship: deploy with validate and Flyway baseline to production during a low-traffic window, with the previous configuration ready to roll back; revoke DDL privileges from the application user once validate is green.

Week four, hygiene: name every generator explicitly, add @Version where aggregates lack it, and start the backlog of expand-and-contract cleanups for the orphaned columns. Trade-offs: a month with no schema changes shipped is the price; communicate it.

What I would not do: switch to validate in production on day one, which will fail on drift you have not catalogued, or hand-write a "clean" schema from the entities and try to migrate production to it in one go.

Land it Baseline what exists, let validate list the drift, reconcile in staging, then take DDL rights away from the application — in that order.

Likely follow-ups
"The drift list has 300 items after week one. How do you triage it?"

By what each item risks. First bucket, blocking: columns the mapping expects that do not exist, or type mismatches that would fail a write, because validate will not boot until they are fixed; these get migrations or mapping fixes immediately.

Second bucket, silent data risk: orphaned columns with data that the mapping ignores, and length or precision mismatches where the database is wider or narrower than the mapping, because these lose or truncate data without failing; these get a decision each and a migration.

Third bucket, cosmetic: nullability and default differences that validate does not check anyway, which go on a backlog. In practice a 300-item list is mostly the third bucket plus a few dozen of the second, and the first bucket is small.

The tally is shared with the team so the month's pause has a visible burn-down.

"How do you handle the fact that the 400 entities will keep changing while you baseline?"

Freeze schema changes, not code changes.

For the month, every pull request that touches an @Entity field mapping needs a migration file, enforced by the CI lint from day one, even before validate is on in production, so no new drift appears while old drift is being catalogued.

Feature work that needs no schema change continues normally.

Changes that genuinely need a column are batched and scheduled after the baseline, or, if urgent, written as migrations that are applied by hand to staging and production and recorded in Flyway, which is the process they will follow from now on anyway.

The communication to the team is one message: from today, schema changes are migrations, and here is the template.

"Why revoke DDL privileges only after validate is green, and not on day one?"

Because with ddl-auto=update still in production, the application needs DDL rights to boot; revoking them on day one makes the next deploy fail on the first ALTER that update attempts, or worse, log the failure and continue with the mapping and schema out of sync.

Once production is on validate with Flyway baselined, the application issues no DDL at all, so revoking is safe and the revocation becomes a guarantee that update can never come back by accident through a configuration change. The migration job keeps a separate role with DDL.

The order is: stop needing the privilege, prove it in staging by booting with the reduced role, then remove it.

"What would you do in week one if the schema dump does not even load cleanly into staging?"

That happens with dumps that reference extensions, roles, or tablespaces that staging lacks, or with objects created by hand outside any tool.

Load it with --no-owner --no-privileges and a role mapping, install the extensions first, and iterate on the errors until the structure loads; the errors are themselves part of the drift inventory, since each names something production depends on that nobody knew about.

If the dump is still unloadable, restore staging from a physical backup of production instead, anonymise the data in place, and dump the schema from there, which sidesteps the dependency order.

The baseline file that goes into Flyway is whatever eventually loads cleanly onto an empty database, tested in CI by loading it on Testcontainers, because that test is what makes the baseline reproducible for every new environment.

Q137 · Design. "Design a safe change of an entity's primary key type from INTEGER to BIGINT on a 1.5-billion-row table with foreign keys from six child tables."

Reveal answer

Strong answer Requirements: the integer key will overflow at 2.1 billion within months; no downtime; child foreign keys must keep matching; rollback possible until the final cut.

A direct ALTER COLUMN TYPE BIGINT rewrites the table and every index and takes an exclusive lock for hours — unacceptable.

Design, PostgreSQL: add id_new BIGINT to the parent and parent_id_new BIGINT to each child, all nullable, instant; a trigger on each table copies the integer value into the new column on insert and update; backfill in keyset batches over days, throttled by replication lag; build unique and foreign-key indexes on the new columns with CONCURRENTLY and add the foreign-key constraints as NOT VALID then VALIDATE CONSTRAINT, which scans without an exclusive lock; then the cutover in one short transaction — drop the old constraints, rename columns (id to id_old, id_new to id), swap primary key to the new unique index with ADD PRIMARY KEY USING INDEX, and switch the sequence's type — milliseconds of lock.

The JPA side: the entity's id field changes from Integer to Long only in the release after the cutover, since the column name is unchanged and a BIGINT reads into either during the transition; Hibernate 7's stricter validation will require the type change promptly.

Trade-offs: doubled storage for the duration; trigger overhead on writes; a long project measured in weeks. Alternative rejected: switching to UUID at the same time, which would change every index's shape and the id generation in one migration — two risky changes in one.

Throughout, alert on the sequence's remaining headroom so the deadline is visible.

Land it Shadow columns, triggers, concurrent indexes, NOT VALID constraints, and a millisecond swap — the type change is a project, not a statement.

Likely follow-ups
"Why does the entity's Java type not have to change until after the cutover?"

Because the JDBC driver converts between the column's type and the requested Java type on read, and on write it binds the Java value as a parameter that the database casts.

An Integer field mapped to a BIGINT column reads fine as long as the values fit in 32 bits, which they do throughout the transition since the old column's values are all below 2.1 billion, and writes bind an int4 that PostgreSQL widens to int8 implicitly.

Hibernate's validate in version 6 tolerated this, and Hibernate 7 reports the width mismatch, so the release immediately after the cutover changes the field to Long, and any sequence value above the integer range is only handed out after that.

The verification is a staging boot on Hibernate 7 with the new column and the old type, to see exactly what validation says before production.

"The requirement changes: the table is on MySQL, not PostgreSQL. What changes?"

The shadow-column approach loses its cheap steps, because InnoDB clusters the table by primary key, so changing the primary key column's type or swapping the primary key rewrites the entire table and every secondary index no matter how you stage it.

The honest MySQL path is an online schema change tool: gh-ost against the parent with MODIFY id BIGINT, which builds a shadow table and swaps it, then gh-ost per child table for each foreign-key column, all throttled by replication lag, over days.

Foreign keys are the complication, since gh-ost does not support tables that are the parent of a foreign key without dropping the constraints first and recreating them after, which is a window with no referential enforcement, mitigated by application-level checks and a reconciliation query.

Weeks of work, but it is a runbook rather than a design.

"How do you keep the child tables' foreign keys valid during the swap?"

In the cutover transaction, the order is: drop each child's old foreign-key constraint on parent_id, rename the parent's columns and swap the primary key to the new unique index, then add each child's foreign key on parent_id_new referencing the new id as NOT VALID, and rename the child columns.

Adding the constraints NOT VALID makes each one a brief metadata operation inside the transaction, and the VALIDATE CONSTRAINT steps run afterwards, one per child, holding only a share lock.

Because the backfill and triggers kept the new columns identical to the old ones, every validation passes.

The whole transaction holds an exclusive lock on the seven tables for the duration of the renames, which is milliseconds if nothing is waiting; a lock_timeout of two seconds makes it fail fast and retry rather than queue behind a long query.

"What is the alert on sequence headroom, concretely?"

A query run every few minutes by the monitoring system: select last_value from orders_id_seq compared against 2147483647, exposed as a gauge of remaining values and a rate of consumption from the difference between samples, giving a projected days-to-exhaustion.

The alert fires at, say, ninety days and again at thirty, so the type change is a planned project rather than an emergency. For every integer primary key in the schema, not just the one someone noticed.

It is ten lines of SQL and a dashboard panel, and it turns the scariest kind of outage, a table that suddenly refuses every insert, into a date on a calendar.

Q138. "Liquibase versus Flyway for a team that must support both PostgreSQL and SQL Server — which, and what is the honest downside of your choice?"

Reveal answer

Strong answer Liquibase, for that requirement.

Its changelog can describe a change abstractly (addColumn, createIndex) and generate the engine-specific SQL, and it supports per-engine SQL blocks with dbms attributes where the abstraction fails — which it does for anything interesting: concurrent index builds, partial indexes, JSON types, identity versus sequence defaults.

It also carries explicit rollback definitions per change set and preconditions, which Flyway's community edition leaves to convention.

The honest downsides: the abstract DSL is verbose and hides what actually runs, so reviewers must read generated SQL anyway; the changelog format encourages large XML or YAML files that merge badly; it runs slower on startup with thousands of change sets; and abstraction invites writing one migration for both engines when the safe migration is genuinely different on each (SQL Server's online index operations versus PostgreSQL's CONCURRENTLY).

Flyway's plain-SQL-per-engine approach (db/migration/postgresql and db/migration/sqlserver locations) is simpler and more honest when the two schemas are allowed to diverge in detail, and is what I would choose if the team is fluent in both dialects.

Either way, the rules that matter — append-only, validate on boot, run once per deploy — are identical.

Land it Liquibase when one changelog must target two engines; Flyway when you would rather write the two dialects honestly — the discipline matters more than the tool.

Likely follow-ups
"How would you structure Flyway locations for two engines without duplicating every migration?"

Three locations: db/migration/common for the majority of migrations that are standard SQL, db/migration/postgresql and db/migration/sqlserver for the engine-specific ones. The property is spring.flyway.locations=classpath:db/migration/common,classpath:db/migration/{vendor}, where Spring resolves {vendor} from the datasource.

Versions are shared across locations, so an engine-specific migration V42 exists in both engine folders with the same number and different bodies, and CI runs the full set against both engines on Testcontainers so a migration that exists for one engine and not the other fails the build.

The common folder stays plain SQL that both engines accept, which in practice means avoiding vendor types and using Flyway placeholders for the few keywords that differ.

"What are the SQL Server specifics that break the abstraction?"

Online index creation is WITH (ONLINE = ON) and Enterprise-only; identity columns versus sequences differ in syntax and in how Hibernate's generator maps; NVARCHAR versus VARCHAR matters for Unicode; there are no partial indexes but filtered indexes with a different syntax; boolean is BIT; there is no RETURNING, but OUTPUT; and transactional DDL exists, unlike MySQL, but with different lock behaviour, schema-modification locks that block readers. JSON support is functions over NVARCHAR(MAX) rather than a type. Any of those in a common migration is where Liquibase's abstract change types either generate something suboptimal or cannot express the safe form, which is why even with Liquibase I would write those change sets as per-engine SQL blocks.

"Your Liquibase changelog has grown to 2,000 change sets and startup takes a minute. What do you do?"

Squash the history. Take a database at the current version, generate a single baseline changelog from it, and start a new changelog that begins with that baseline marked as already applied on existing environments through changelogSync; new environments run the baseline.

The old changelog is archived in version control for audit. Liquibase then has one change set to check plus the new ones, and startup is back to seconds.

Do it at a quiet point and test the new-environment path on Testcontainers to confirm the baseline creates the same schema, using a schema diff. The same technique applies to Flyway with a new baseline version and baselineOnMigrate.

It is an annual chore for a fast-moving schema and not a reason to avoid either tool.

"Does the choice change if the team adds a third engine next year?"

It strengthens the argument for the abstract layer where it works and per-engine SQL where it does not, which both tools support in their own way, so the choice does not flip.

What changes is the CI cost: three engines on Testcontainers per build, which is the real price of multi-engine support and the reason to ask whether the product needs it.

Hibernate's side is easier than the migration side, because dialects handle most query differences, but the mapping must avoid engine-specific types and features, which means no PostgreSQL enums, no JSONB operators, no @Formula with vendor functions.

The honest answer is that every engine added roughly doubles the schema and query testing effort, and the tool choice is a small part of that.

Drill · Design & judgment

This group tests the senior question underneath all the others: given these requirements, what would you build — and what would you refuse to build?

Q139 · Design. "Design the entity model and repositories for a ledger where every balance change is an immutable entry and balances must be exact and fast to read."

Reveal answer

Strong answer Requirements: append-only entries, exact arithmetic, a balance readable in one indexed lookup, concurrent postings that never lose an entry or double-spend, and an audit trail that is the data itself.

Design: LedgerEntry as an @Immutable entity — id (sequence, batched), accountId, amount as BigDecimal in a NUMERIC(19,4), currency, postedAt, idempotencyKey with a unique constraint; no updates, no deletes, no relationships beyond the account id.

AccountBalance as a separate row per account with balance and @Version, updated in the same transaction as the entry insert with an atomic update account_balance set balance = balance + :amount, version = version + 1 where account_id = :id and balance + :amount >= :floor whose update count enforces the overdraft rule — no load-modify-save, so no optimistic-lock storm (Q64).

Reads of the balance are one primary-key lookup; a nightly job recomputes each balance from entries and alerts on drift. Repositories: LedgerEntryRepository exposes only save and keyset-paged queries; AccountBalanceRepository exposes the atomic @Modifying update and findById.

Trade-offs: the balance row is denormalised state, kept honest by the reconciliation job; the atomic update bypasses entity callbacks, so the entry row is the audit, not a listener.

What I would not do: compute balances by summing entries on every read (fine at ten thousand entries, not at ten million), or let the balance be a JPA-managed field that the dirty check writes.

Land it Immutable entries plus an atomically updated balance row — the ORM inserts the history and one SQL expression keeps the present.

Likely follow-ups
"The requirement changes: the balance must be exact as of any past date. What changes?"

The entries already give it, since a balance at date D is the sum of entries with postedAt up to D, and that query is an indexed range scan on (account_id, posted_at).

For accounts with millions of entries the sum is slow, so the design adds periodic snapshots: a balance_snapshot row per account per day, written by the nightly reconciliation job that already recomputes balances, and a historical balance query is the latest snapshot before D plus the entries between the snapshot and D, which is bounded to a day's worth.

The live balance row stays as it is for the hot path. Nothing about the entry table changes, which is the property of an append-only design: new requirements are new readers, not new writers.

"Under time pressure, what would you cut from the ledger design?"

I would cut the reconciliation job and the idempotency key, in that order, and neither for long.

The reconciliation job is safety, not function; the atomic balance update is correct on its own, and the job catches bugs and manual edits, so it ships in the second week.

The idempotency key is cut only if the callers are known not to retry, which is rarely true, so it ships with the first client that retries.

I would not cut the atomic update in favour of load-modify-save with @Version, because under concurrent postings the version conflicts become the throughput ceiling and the retry storm from Q123; and I would not cut BigDecimal for a long of minor units, though that is a legitimate design if the currencies all have fixed minor units.

"How does the atomic update return the new balance to the caller without a second SELECT?"

With RETURNING on PostgreSQL. The repository method is a native query: @Query(value = "update account_balance set balance = balance + :amt, version = version + 1 where account_id = :id and balance + :amt >= :floor returning balance", nativeQuery = true), and because it is a native query that returns a value, it is declared without @Modifying and returns Optional<BigDecimal>; an empty result means the overdraft rule refused the update.

Hibernate runs it as a query, so the AUTO flush fires beforehand, and the persistence context is not updated, which is fine because the balance row is never loaded as an entity in this path.

On MySQL there is no RETURNING, so it is the update followed by a select in the same transaction, two statements. The entry insert goes in the same transaction so the two are atomic.

"What does the idempotency key protect against, and where is it checked?"

Against the same posting applied twice by a retrying client or a redelivered message.

The key, supplied by the caller and stored on the entry with a unique constraint, makes the second insert fail with a constraint violation; the balance update in the same transaction is then rolled back with it, so the balance is not double-changed.

The check is therefore the database, not a lookup: the transaction inserts the entry first, with an immediate flush() so the violation is raised inside the method, and only then updates the balance.

On the violation, the caller looks up the existing entry by key and returns it as the result, which is the Q143 pattern. A cache-based check would forget keys on restart; the unique index does not.

Q140 · Design. "When would you NOT use an ORM at all for a new service? Give the decision rule and an example on each side."

Reveal answer

Strong answer The rule: an ORM pays for itself when the service's core work is loading a graph of objects, applying business rules to it, and saving what changed — because dirty checking, cascades, identity and optimistic locking are exactly that bookkeeping, and hand-writing them is where bugs live.

It does not pay when the work is set-oriented, read-heavy, or SQL-shaped.

Skip it for: an analytics or reporting service whose queries are joins, window functions and aggregations over millions of rows — use jOOQ or Spring's JdbcClient with records, where the SQL is visible and the plan is reviewable; an event-ingestion pipeline that inserts a hundred thousand rows a second and never reads them back as objects — batched JDBC or COPY; a service over a schema you do not own with composite keys and no surrogate ids, where the mapping fights you daily.

Use it for: the orders service in this primer, a subscription-management domain with state machines and invariants, anything with aggregates edited by users.

The middle ground is common and legitimate: JPA for the write model and jOOQ or projections for the read side in the same service, which is what most mature Spring codebases converge on.

What I would not do: pick "no ORM" because of one N+1 someone once saw — that is a tuning problem with a known fix — or pick JPA for a reporting service because the team knows it.

Land it Object graphs with rules: ORM. Sets, streams and analytics: SQL. Most services need both, split by write model and read model.

Likely follow-ups
"What does jOOQ give the read side that a JPA projection does not?"

The full SQL vocabulary with compile-time checking. Window functions, common table expressions, lateral joins, FILTER clauses, JSON aggregation, engine-specific upserts, all typed against generated classes from the schema, so a renamed column is a compile error rather than a runtime exception.

JPQL covers a growing subset, Hibernate 6 and 7 added window functions and CTEs, but the dialect-specific parts still need native queries as strings, which are untyped.

jOOQ also returns records or DTOs with no persistence context involvement, like a projection, and its fetch API streams and pages naturally.

The costs are code generation as a build step, a second query model for the team to learn, and the temptation to write updates in jOOQ that bypass the aggregate's invariants, which the golden path forbids.

"How do the two coexist in one transaction?"

Through the same connection. jOOQ's DSLContext is configured with a DataSourceConnectionProvider over Spring's TransactionAwareDataSourceProxy, so a jOOQ query inside a @Transactional method uses the transaction's connection and sees the transaction's uncommitted writes, and Spring's JpaTransactionManager commits both.

The caveat is flush order: Hibernate's pending changes are not in the database until flush, and jOOQ does not trigger Hibernate's AUTO flush, so a jOOQ read after a JPA write in the same transaction must be preceded by em.flush() or it reads stale rows.

I wrap that in a small helper so it is never forgotten, and I keep the pattern rare: a transaction either mutates aggregates through JPA or reads through jOOQ, and mixing is the exception with a comment.

"A team wants to use JPA for event ingestion anyway because they know it. What is the concrete cost?"

Per row: entity instantiation, a snapshot array, an identity-map entry, and a flush-time dirty check, none of which the ingestion needs; plus an id from a sequence, which with a pooled optimizer is cheap, or from IDENTITY, which kills batching.

At a hundred thousand rows per second that is a hundred thousand objects and arrays per second on the heap for nothing, and the clear-every-N discipline that people forget.

The practical number: a batched StatelessSession or plain JDBC batch reaches tens of thousands of rows per second per thread on a modest database; a stateful session with cascades manages a fraction of that and grows the heap until cleared.

The compromise for a team that knows JPA is the StatelessSession, which keeps the mapping and drops the machinery, and it takes an afternoon to learn.

"What is the decision rule's failure case? When has 'object graph with rules' misled you?"

When the graph is wide but the rules are shallow.

A configuration domain with hundreds of entity types and deep hierarchies but almost no invariants beyond "not null" gets a heavy mapping, a large persistence context, and no benefit from dirty checking, because nothing ever changes a loaded object except an admin form.

The rule says ORM; the reality is that a document store or a JSON column with a few tables would have been simpler. The tell is that the entity classes have getters and setters and nothing else, and the services are mappers.

So the refinement is: object graphs with behaviour, where methods on the aggregate enforce rules. A graph of data-holders is a schema, and a schema is served as well by records and SQL.

Q141 · Design. "Design how the orders service exposes read models for three consumers — the web app, a mobile API, and a data warehouse — without letting entities leak or the database melt."

Reveal answer

Strong answer Requirements: each consumer gets the shape it needs, none of them can trigger lazy loads or N+1s, the warehouse's bulk reads do not compete with user traffic, and the write model stays free to change.

Design: the write model — JPA entities, transactions, invariants — is private to the service.

Web and mobile get record projections from dedicated query classes (one per screen: OrderListQuery, OrderDetailQuery) that return DTOs built inside readOnly transactions with explicit fetch plans (Q91); the two APIs differ in fields, so each has its own record, and the mobile list omits line details to keep payloads small (E6 covers versioning the contracts).

Hot read models — the order detail page — are cached as response JSON with invalidation from the write path's outbox (Q109).

The warehouse never queries the service's database: it consumes change events from the outbox topic (or a CDC stream of the orders tables) into its own store, so its full scans happen on its hardware, and a nightly reconciliation compares counts.

Trade-offs: three read shapes is more code than one entity serialised three ways, and the warehouse's data is seconds behind; in exchange, the entity classes can be refactored without breaking any consumer, and user latency is unaffected by warehouse loads.

What I would not do: give the warehouse a read replica connection to the JPA schema, which couples their tables to my mapping forever; or return entities with @JsonView annotations to pick fields per consumer, which is entity leakage with extra steps.

Land it Private write model, one projection per screen, cached responses for hot reads, and events for the warehouse — nobody but the service ever sees an entity.

Likely follow-ups
"The requirement changes: the mobile team wants to choose fields per request, GraphQL-style. Does the design hold?"

It holds if the field selection is applied to a fixed read model, not to the entity graph.

The mobile query class returns a superset record for the mobile screen, and a field-selection layer filters the response JSON by the requested field set; the SQL stays one projection with a bounded column list.

What I refuse is a resolver per entity association, where the client's field selection walks order.customer.address.country through lazy loads, because that is the client choosing the N+1.

If true GraphQL is required, the resolvers use data loaders that batch by id, and each data loader is a projection query with an IN list, which is batch fetching reinvented at the API layer and is fine.

The principle survives: the client selects from what the service prepared, and the service controls the statements.

"Under time pressure, which consumer gets the shortcut and what is the shortcut?"

The warehouse, and the shortcut is a nightly export rather than a change stream.

A keyset-chunked COPY of the orders tables to object storage, as in Q100, gives the warehouse a daily snapshot with one job and no outbox consumer on their side, and it can be replaced by the event stream later without changing their schema, since the export and the events carry the same columns.

The web and mobile projections are not shortcut, because their alternative is entity serialisation, which is the incident class this whole design exists to prevent. The response cache is deferred until the latency numbers ask for it.

The cut costs the warehouse a day of freshness, which for most analytics is fine and is stated in writing.

"Why does giving the warehouse a read replica couple their tables to your mapping forever?"

Because every column and table name becomes part of a contract you did not write and cannot see.

The warehouse's pipelines select from orders and order_line by name; the day you rename status to state through the Q129 sequence, their pipeline breaks at the drop step, and you learn about it from their on-call.

Every normalisation choice, every embeddable's column names, every enum's string values is frozen. With events or an export, the contract is explicit, versioned with the schema-evolution rules from E6, and changed with notice.

The replica also puts their full-table scans on your database's cache and I/O, which affects your latency without any signal in your metrics. The coupling is invisible until it hurts, which is the worst kind.

"How do you keep three record types per screen from becoming a maintenance problem?"

By making them cheap to write and hard to misuse. Each record lives next to its query class, has no logic, and is constructed by a JPQL constructor expression or a mapper method, so adding a field is one line in three places.

A test per query asserts the statement count and the field set. Where two consumers genuinely share a shape, they share one record; the rule is one record per shape, not per consumer, so three consumers might use four records rather than nine.

MapStruct or a hand-written mapper handles nested shapes. The alternative, one entity serialised with per-consumer views, saves those files and costs every incident in the fetching drill, which is a bad trade. Explicit records are the boring answer and the right one.

Q142 · Scenario. "A new team member proposes replacing all Spring Data repositories with Hibernate 7's Jakarta Data repositories. What do you tell them?"

Reveal answer

Strong answer First, what they are: Jakarta Data is a specification for repository interfaces — @Repository interfaces with @Find, @Query (JDQL), @Insert, @Update and @Delete methods — and Hibernate's annotation processor (hibernate-processor) generates the implementation at compile time, so query errors are compile errors and there is no runtime proxy.

That is a genuine advantage: type-checked queries, no reflection, faster startup, and it fits Quarkus and plain Jakarta EE. What I would say: the value is real but the migration cost in a Spring Boot service is not worth it today, for three reasons.

Spring Data's integration with Spring's transaction management, its Pageable/Sort/Specification ecosystem, projections, auditing, and @Modifying semantics are what our code relies on, and Jakarta Data covers only part of that surface; Spring Data 4 already addresses the startup and reflection cost with AOT repositories that generate query implementations at build time; and running two repository models side by side confuses the transaction boundaries (Q14) and the team.

Where I would try it: a new, small module with simple queries, as an experiment — or if the service moves off Spring.

A fair compromise: adopt Hibernate's static metamodel and the processor for type-safe criteria today, which is the same tooling without changing the repository layer.

Land it Compile-time repositories are the right direction, and Spring Data 4's AOT gets us most of it without replacing the layer our transactions depend on.

Likely follow-ups
"What does a Jakarta Data repository look like, side by side with the Spring Data one?"

Spring Data: interface OrderRepository extends JpaRepository<Order, Long> { List<Order> findByStatus(Status s); }, implemented at runtime by a proxy that parses the method name.

Jakarta Data: @Repository interface Orders { @Find List<Order> byStatus(Status status); @Query("where status = :s order by createdAt desc") List<Order> recent(Status s); @Insert void add(Order o); @Delete void remove(Order o); }, implemented by hibernate-processor at compile time as a concrete class using a StatelessSession or EntityManager injected by the container.

The @Find parameters must match entity property names or the build fails; a JDQL query that references a missing property is a compile error.

As of Aug 2026 Hibernate 7.x implements Jakarta Data 1.0, and Spring Boot does not auto-configure Jakarta Data repositories, so wiring them in a Spring service is manual.

"What are AOT repositories in Spring Data 4, and how much do they close the gap?"

Spring Data 4, with Spring Boot 4 as of Nov 2025, can generate repository implementations ahead of time as Java source during the build: derived method names are parsed once at build time and turned into concrete methods with the JPQL already written, which removes the runtime proxy and the reflection-based parsing, speeds startup, and makes the generated query visible in source for review.

It closes the startup and transparency gap.

It does not give compile-time validation of the query against the entity model in the same way, since the generated JPQL is still validated by Hibernate at runtime unless the Hibernate processor's query validation is also enabled, which it can be.

The combination, Spring Data AOT plus hibernate-processor validating @Query strings at compile time, gets most of the Jakarta Data benefit without changing the repository interfaces.

"If the team did adopt Jakarta Data in a module, what would break first?"

Transactions.

Jakarta Data repositories generated by Hibernate obtain a session from the container; in a Spring application the injected EntityManager must be Spring's shared proxy so that it participates in @Transactional, and a repository built on a StatelessSession is outside Spring's persistence context entirely, so a JPA write and a Jakarta Data read in the same transaction see different state.

The second thing is exception translation: Spring's DataAccessException hierarchy comes from the repository post-processor, which Jakarta Data repositories bypass, so callers catching DataIntegrityViolationException get Hibernate's exception instead. The third is auditing and @Version handling on @Update, which follow Jakarta Data's rules, not Spring Data's. All solvable, all reasons for a small module first.

"What would make you change your recommendation?"

Three signals. Spring Boot shipping first-class Jakarta Data auto-configuration with transaction integration, which would remove the wiring cost and the transaction risk.

The service moving to a runtime where Spring Data is not the natural fit, Quarkus or plain Jakarta EE, where Jakarta Data is the native repository model.

Or a measured need: a startup time budget that the AOT repositories cannot meet, or a bug class from runtime-parsed queries that the team keeps hitting, both of which compile-time repositories address directly.

Absent those, the recommendation is to adopt the tooling that gives compile-time safety within Spring Data, and to keep a small Jakarta Data module as a learning exercise so the team is ready if the signals arrive.

Q143 · Design. "Design idempotent order creation through JPA so that a client retrying a POST after a timeout never creates two orders, under concurrent retries."

Reveal answer

Strong answer Requirements: at most one order per client idempotency key, correct under two retries arriving at the same time on different pods, and the retry returns the original result.

Design: the client sends an Idempotency-Key header; the orders table has an idempotency_key column with a unique constraint (or a separate idempotency_record table keyed by client id plus key, holding the response).

In the @Transactional create method: insert the order with the key first — with SEQUENCE ids the INSERT is deferred, so flush() immediately after persist() to hit the unique constraint now, inside the method, rather than at commit outside it (Q125).

On DataIntegrityViolationException for that constraint, the transaction is dead; catch it in the non-transactional caller, look up the existing order by key in a fresh transaction, and return it with the original status code.

Under concurrent retries, the database's unique index serialises them: exactly one INSERT wins, the other fails at flush and falls into the lookup path, which may need a brief retry if the winner has not committed yet (READ COMMITTED sees it after commit).

Trade-offs: the flush costs an early round trip; the alternative of SELECT ... FOR UPDATE on an idempotency record first is heavier under contention. What I would not do: check-then-insert without the constraint, which races; or store idempotency state in a cache that can forget it.

Land it A unique constraint on the key, a flush that makes the conflict happen inside your method, and a lookup on conflict — the database is the arbiter, not a cache.

Likely follow-ups
"The lookup after the conflict returns nothing because the winner has not committed. Walk through the exact retry."

Under READ COMMITTED the loser's insert blocks on the winner's uncommitted unique-index entry until the winner commits or rolls back, and only then fails with the violation; so by the time the loser catches the exception the winner has committed, and the lookup in a new transaction finds the order.

The empty-lookup case arises when the winner rolled back, in which case the loser should retry the whole create, since the key is now free.

So the caller's loop is: try create; on unique violation, look up by key; if found, return it; if not found, retry the create up to two more times.

The unique index provides the serialisation and the database's blocking behaviour provides the ordering, which is why this works without any application-level lock. A test with two threads and a latch before commit proves both branches.

"How do you make sure the retry returns the original response, including the status code and the body?"

By storing the response, not just the order. The idempotency record holds the key, the request's fingerprint, a hash of the body, the resulting order id, the HTTP status, and the serialised response body, written in the same transaction as the order.

A retry with the same key and the same fingerprint returns the stored body and status verbatim; a retry with the same key and a different fingerprint returns 422, because the client is reusing a key for a different request, which is a bug worth surfacing.

The record has a retention period, a day or a week, after which a repeated key is treated as new, and the client documentation says so.

Storing only the order id would make the retry rebuild the response from current state, which can differ from what the original call returned.

"Why is the flush inside the method necessary? Would the constraint not fire at commit anyway?"

It would, but at commit the exception surfaces from the transaction proxy after the method has returned, so nothing inside the method can catch it, and the caller receives a translated exception with the transaction already rolled back.

That is workable if the caller is designed for it, which is the pattern in the answer.

The flush moves the failure earlier for two reasons: any work after the insert, such as reserving stock or publishing an outbox row, is skipped when the insert has already failed, rather than done and rolled back; and the error is raised at the line that caused it, which makes the code readable and the retry loop simpler.

With IDENTITY ids the insert is immediate and the flush is implicit; with SEQUENCE ids, which the golden path uses, the flush is needed.

"What would you cut under time pressure, and what is the risk of the cut?"

I would cut the stored response and return the existing order from a lookup, so a retry can in rare cases see a later state, for example a status that moved from CREATED to CONFIRMED, which for a create endpoint is acceptable and documented.

I would cut the fingerprint check, accepting that a client reusing a key for a different order gets the first order back rather than an error, which is a client bug we would discover later.

I would not cut the unique constraint or the conflict handling, because without them two concurrent retries create two orders, which is the incident the design exists to prevent, and it is only twenty lines.

The cuts save a table and a few lines; the keeps are the correctness.

Q144 · Design. "Design a multi-currency Money type across entities, queries and the schema, so that no amount can ever be stored or summed without its currency."

Reveal answer

Strong answer Requirements: amount and currency always travel together, exact decimal arithmetic, correct summation only within one currency, and queries that can filter and aggregate by currency.

Design: Money as a Java record marked @Embeddable — BigDecimal amount with @Column(precision = 19, scale = 4) and String currency (ISO 4217, length 3) — embedded wherever money appears with @AttributeOverrides to name the columns (total_amount, total_currency).

The record's methods enforce the rules: add throws on currency mismatch; there is no getAmount-only arithmetic path. Both columns NOT NULL in the migrations with a CHECK that currency is in the supported set.

In JPQL, aggregates are written as select o.total.currency, sum(o.total.amount) from Order o group by o.total.currency, returning a record per currency, never a bare sum; a code-review rule (or an ArchUnit test on query strings) forbids sum(...amount) without a matching group by ...currency.

Conversion is a separate domain service with dated rates, never a method on Money.

Trade-offs: two columns per amount and a small amount of annotation noise; an alternative single NUMERIC with a currency at the aggregate level is simpler but fails the moment one aggregate mixes currencies.

What I would not do: double, a currency stored on a parent that children silently inherit, or a custom AttributeConverter that packs both into one string column, which makes aggregation in SQL impossible.

Land it An embeddable record with both columns NOT NULL and arithmetic that refuses mismatches — the type carries the rule, and the schema backs it up.

Likely follow-ups
"How does an embeddable record work with Hibernate, given records have no setters or no-arg constructor?"

Hibernate 6.2 and later, and Jakarta Persistence 3.2, support records as embeddables by instantiating them through the canonical constructor.

Hibernate reads the column values for the components and calls the constructor with them in declaration order, matching by name; on write it reads the components through the accessor methods.

The record must be annotated @Embeddable and the components need column annotations directly on the record components.

What does not work is mutation: an entity holding a Money total replaces the whole value with a new record when the amount changes, this.total = total.plus(x), which is exactly the value-object semantics you want and which the dirty check handles as a change to both columns.

A verification test persists an order, reloads it after clear(), and asserts the record's equality.

"What about the null case: an order with no total yet? Both columns NOT NULL breaks that."

Then the requirement has to be stated precisely.

If a total can be absent, the embeddable is nullable as a whole, and Hibernate maps a null Money as both columns null, so the constraint becomes a check that they are null together or set together: CHECK ((total_amount IS NULL) = (total_currency IS NULL)).

That preserves the rule that no amount exists without a currency while allowing absence.

If a total must always exist, the entity's constructor requires it, and the columns stay NOT NULL. What I refuse is a zero amount with a null currency as a stand-in for absence, because it makes zero and unknown indistinguishable in SQL. The check constraint is the schema saying the same thing the record says.

"How would you make the JPQL aggregation rule enforceable rather than a review comment?"

Two mechanisms.

A test that scans every @Query annotation and named query in the codebase through reflection, finds those containing sum( over a path ending in .amount, and asserts that the same query string contains a group by including the sibling .currency path; a query that violates it fails the test with its location.

And a repository-level convention: money aggregations are exposed only by a MoneyAggregateRepository whose methods return List<CurrencyTotal> records with both fields, so callers cannot get a bare BigDecimal total from anywhere. The test catches the mistake in the query; the type catches it in the caller.

A rule that exists only in a document is followed until the first hurried Friday.

"Why not a single NUMERIC column and the currency at the aggregate level, since most orders are one currency?"

Because "most" is the problem. The moment one order has a line in a second currency, or a refund in the original currency after the customer's account currency changed, every sum over lines in that aggregate is wrong, and nothing in the schema stops it.

The two-column design costs a few bytes per amount and a slightly longer @AttributeOverrides block; the single-column design saves those and moves the correctness burden onto every developer who writes a sum.

If the domain genuinely guarantees one currency per aggregate as an invariant, the order carries a currency and the lines carry amounts, with a check in the aggregate's addLine that rejects a mismatched currency, and the line's Money still includes the currency column, redundantly, so the schema can enforce it with a foreign-key-like check. Redundancy in the schema is cheaper than a wrong invoice.

Q145. "Cross-cutting with E3: a service's threads are all blocked in HikariPool.getConnection and the JVM shows 200 threads in that state. Is this a Hibernate problem, a pool problem, or a Java problem, and how do you tell?"

Reveal answer

Strong answer It is a symptom with three possible owners, and the thread dump plus Hikari's metrics tell them apart. Look at the threads that hold connections, not the ones waiting.

If the holders are inside JDBC calls — socketRead under a PreparedStatement.execute — the database is slow or locked: a database problem, diagnose with pg_stat_activity and lock waits (E8).

If the holders are in application code — an HTTP client call, a Kafka send, a Thread.sleep, a lock — while a transaction is open, it is a transaction-boundary problem: Hibernate holds the connection for the whole @Transactional method (Q18, Q36), and the fix is moving the I/O out or delayed acquisition.

If no thread holds a connection but the pool reports all active, it is a leak — a connection borrowed outside Spring's management (a manual DataSource.getConnection() without close, or a Stream from a repository never closed); Hikari's leakDetectionThreshold logs the stack of the borrower.

If the holders are few and fast but waiters are many, it is capacity — a Java-level concurrency problem where 200 request threads exceed a pool of 10 under a traffic spike, and the answer is admission control and pool sizing (Q111), not a bigger pool alone.

The E3 tuning section walks the same triage from the JVM side.

Land it Read the holders, not the waiters: JDBC frames mean database, application frames mean transaction shape, no holders mean a leak, and short holders with long queues mean capacity.

Likely follow-ups
"What exactly do you look for in the thread dump, and how do you get one quickly?"

jcmd <pid> Thread.print or kill -3, three of them ten seconds apart so you can see which threads move. Search for HikariPool.getConnection and count the waiters, then search for ProxyConnection or HikariProxyConnection frames to find threads that hold a connection, and read up their stacks.

A holder inside PgStatement.executeInternal and socketRead0 is waiting on the database. A holder whose stack shows HttpClient.send or KafkaProducer.send above a TransactionInterceptor frame is doing I/O inside a transaction. No holder at all with a full pool is a leak.

With virtual threads the dump needs jcmd <pid> Thread.dump_to_file -format=json, since Thread.print omits them. Ten minutes of reading tells you which of the three owners it is.

"How does leakDetectionThreshold work, and what is its cost?"

Hikari records the stack trace at each connection borrow and starts a timer; if the connection is not returned within the threshold, say leak-detection-threshold: 20000 milliseconds, it logs a warning with the borrower's stack and, when the connection is finally returned, a second message saying it was not a leak after all.

The cost is capturing a stack trace per borrow, a few microseconds, and the risk of noise from legitimately long transactions such as batch jobs, which is why the threshold is set above the longest expected transaction and the batch jobs get their own pool.

It does not close the connection or fix anything; it names the code. I run it in production at a generous threshold permanently, because the day a leak appears, the stack trace in the log is the whole investigation.

"If it is capacity, how do you distinguish 'a spike we should absorb' from 'a pool that is too small'?"

By the database's utilisation during the wait. If the database CPU is under 50 percent and its own active sessions are all fast, the pool is the constraint and can grow, since the database has room for more concurrent work; the growth is tested by raising the pool on one pod and watching its latency and the database's CPU. If the database is near saturation, the pool is correctly sized and the spike must be shed or queued in the application with a short connection-timeout and a semaphore, because more connections would only lengthen the database's run queue. The Hikari usage histogram gives the transaction time; the number of transactions per second times that time is the pool's occupancy, and comparing occupancy with pool size says how far over capacity the spike is.

"With virtual threads, does '200 threads blocked in getConnection' mean the same thing?"

It means more. With platform threads, 200 was the Tomcat maximum, so the number itself was the cap and told you the thread pool was exhausted as well.

With virtual threads there is no such cap, so 200 blocked in getConnection could be 2,000 next minute, and the JVM shows no thread exhaustion because virtual threads are cheap. The pool is the only backpressure, which is the Q112 point.

The triage steps are the same, but the capacity answer changes: the application must now bound its own concurrency explicitly, because nothing else does.

I would also check for carrier-thread pinning in the dump, since a few pinned carriers in JDBC reads make the effective parallelism far lower than the number of virtual threads suggests.

Q146 · Design. "Design the JPA configuration and conventions for a new Spring Boot 4 service as a one-page 'golden path' for a team of eight."

Reveal answer

Strong answer Configuration, from the primer's application.yml: open-in-view: false; ddl-auto: validate with Flyway; batch_size: 50, order_inserts, order_updates; default_batch_fetch_size: 50; fail_on_pagination_over_collection_fetch: true; Hikari auto-commit: false with provider_disables_autocommit; pool size and connection-timeout explicit; hibernate.jdbc.time_zone: UTC; statistics on with Micrometer export; SQL logging at DEBUG only in the test profile.

Mapping conventions: SEQUENCE ids with allocationSize = 50 and named generators; @Version on every aggregate root; every association LAZY; Set for unordered collections; cascade and orphan removal only from root to owned children; no cascade on @ManyToOne; @Enumerated(STRING); Instant in timestamptz; BigDecimal for money in an embeddable; id-based equals/hashCode, no Lombok @Data on entities.

Code conventions: transactions on service methods only, readOnly on reads, no I/O inside transactions, DTO records at every boundary, projections for lists, join fetch or entity graphs per query, bulk statements in their own methods with clearAutomatically.

Testing: Testcontainers PostgreSQL with migrations, assertSelectCount on every endpoint test, ArchUnit rules enforcing the entity and controller rules. What I would leave out: the second-level cache (Q115), @DynamicUpdate by default, and any hibernate.enable_lazy_load_no_trans.

A one-page document with these three lists, linked from the repository's README, is the artefact.

Land it The golden path is three short lists — configuration, mapping, code — each item preventing a specific incident from this drill.

Likely follow-ups
"Which item on the golden path do new team members push back on most, and how do you answer?"

Two: no @Data on entities, and no entities returned from controllers. The first is answered by the Q78 stack trace and the N+1 from a log statement; the argument is a five-minute demonstration on their own laptop.

The second is answered by the lazy-loading exception that appears only in production and the JSON that changes shape when someone adds a field to the entity; the counter-argument is that records are one line each and the mapper is boring, which is the point.

What I do not do is enforce by rule alone.

Every item on the page links to the drill question it prevents, so the pushback conversation is about the incident rather than the preference, and the ArchUnit tests make the decision once rather than in every review.

"How do you enforce the golden path mechanically, beyond ArchUnit?"

Four layers. A starter module or a shared Gradle convention plugin that sets the configuration defaults, so every new service starts with open-in-view: false, batching, validate, and the Hikari settings without copying a file. ArchUnit rules for the code conventions, in the shared test library.

A Testcontainers base class and the statement-count assertion helper in the same library, so writing the honest test is easier than writing a dishonest one. And a CI lint for migrations.

Together these mean a team of eight follows the path by default and departs from it only deliberately, with a visible exclusion. The document remains the explanation; the tooling is the enforcement.

Reviewing eight people's pull requests for these rules by hand does not scale and becomes inconsistent within a month.

"Under time pressure, which three items would you insist on if you could only get three adopted?"

open-in-view: false, ddl-auto: validate with migrations, and all associations LAZY with a statement-count test on each endpoint. The first prevents the pool-exhaustion and hidden-query class; the second prevents the schema-drift and concurrent-DDL class; the third prevents the N+1 and in-memory-pagination class.

Between them they cover most of the incidents in this drill. Batching, @Version, and the DTO rule follow in the second round, and I would still argue for @Version early on any aggregate touched by a job, because the Q126 lost update is silent.

The rest of the page is refinement that the team adopts as each item's incident shows up in a retrospective, which is when it lands.

"What would you add to the golden path for Spring Boot 4 specifically, as of now?"

Four things, as of Aug 2026. Declare spring-boot-starter-data-jpa explicitly, because the modular auto-configuration no longer arrives transitively. Enable Spring Data's AOT repository generation in the build so query derivation happens at compile time and the generated JPQL is reviewable.

Add hibernate-processor as an annotation processor for the static metamodel and for compile-time validation of @Query strings.

And decide the virtual-thread setting deliberately: if spring.threads.virtual.enabled is on, the golden path includes an explicit concurrency bound in front of the transactional layer and a pool sized from the database, with the Hikari connection-timeout at two seconds.

Plus the Hibernate 7 mapping checklist: no @GenericGenerator, Instant on timestamptz, and @UuidGenerator where UUIDs are used.

Q147 · Design. "Design a soft-launch strategy for switching an existing service from IDENTITY ids on MySQL to application-generated UUID v7, with rollback."

Reveal answer

Strong answer Requirements: unlock batched inserts and cross-service id generation, no downtime, existing ids and foreign keys preserved, rollback for at least one release. Design: the existing id BIGINT AUTO_INCREMENT stays the primary key through the transition.

Phase one: add public_id BINARY(16) nullable with a unique index built online (ALGORITHM=INPLACE, LOCK=NONE) to every affected table; new code generates a UUID v7 in @PrePersist and writes it; a backfill sets it for existing rows in batches.

Phase two: external APIs and events start exposing public_id instead of the numeric id (E6 on identifier contracts), with a lookup-by-either window.

Phase three, the mapping switch: the entity's @Id becomes the UUID (@UuidGenerator(style = VERSION_7)), the numeric column becomes a plain mapped field, and foreign keys are migrated to reference the UUID — which on MySQL is where the cost lives, because InnoDB clusters the table by primary key and changing it rewrites the table: use gh-ost per table, one at a time, starting with the smallest.

Only after phase three does batching work for inserts. Rollback: through phase two, nothing depends on the UUID being primary; in phase three, each table's swap is independently reversible with gh-ost until the numeric column is dropped, which is never before a release has run clean.

Trade-offs: 16-byte keys in every secondary index, and weeks of dual identity. What I would not do: switch the primary key and the API identifiers in one release, or use random UUID v4 on InnoDB (Q44).

Land it Add the UUID as a second identity, move the contracts to it, then swap the primary key table by table with an online tool — batching is the reward at the end, not the first step.

Likely follow-ups
"Why is v7 acceptable as an InnoDB primary key when v4 is not?"

Because InnoDB stores the table's rows in the primary-key B-tree, so inserts land at the position of the new key.

With random v4 keys, every insert goes to a random leaf page, which means page splits, a working set that is the whole index rather than its right edge, and a buffer pool that thrashes once the index exceeds memory; the effect on a large table is inserts several times slower and secondary indexes that are also random by the primary key they carry.

UUID v7 puts a millisecond timestamp in the leading 48 bits, so consecutive inserts are near each other in key order, and the B-tree grows at its right edge like an auto-increment, with the random tail only ordering within a millisecond.

Stored as BINARY(16), the byte order preserves the time ordering. The insert throughput on a large table is close to the numeric key's.

"Under time pressure, could you stop at phase two and still get value?"

Yes, and it is a legitimate end state for a while. After phase two the external contracts use the UUID, so other services can generate references without calling this one, ids are no longer guessable, and the numeric id is an internal detail.

What you do not get is batched inserts, since the primary key is still IDENTITY, and the join columns are still numeric, so foreign keys keep working exactly as before with no rewrite risk. Many teams stop here for a year.

The phase-three swap is scheduled when a measurement, the six-hour import or an insert-bound job, shows that batching is worth a table rewrite per table.

Stopping at phase two is a decision to record, not a failure, and the rollback story is trivial because nothing has changed under the hood.

"How does Hibernate know the id is set before insert, and what is different from IDENTITY in the flush?"

With @UuidGenerator Hibernate generates the value in memory when persist() is called, so the entity is assigned an id immediately and the INSERT is queued for the flush, where it joins the JDBC batch with the other inserts of the same table.

With IDENTITY, the id does not exist until the database assigns it, so Hibernate must execute the INSERT at persist() time to retrieve the generated key, which is why batching is impossible and why persist() on an IDENTITY entity hits the database immediately.

During the transition, the entity has both a generated numeric id and a generated UUID; the @PrePersist hook sets the UUID because the primary key is still IDENTITY, and after the swap the @UuidGenerator on the id takes over and the hook is removed.

Verification is the batch size in the proxy log going from one to fifty after phase three.

"What does the API 'lookup-by-either' window cost, and how do you end it?"

Every endpoint that takes an id must accept both forms, detect which by shape, a UUID pattern versus digits, and query by the matching column, both of which are indexed, so the runtime cost is a branch and no extra statements.

The maintenance cost is the branch in every controller and the ambiguity in logs.

Ending it needs a measurement: log which form each caller uses, with the caller's identity, and when the numeric form has been unused for a full release cycle by everyone but a known laggard, contact the laggard with a date, then remove the numeric path and return 400 for digits.

The cost of keeping it forever is small per endpoint and large in aggregate, because it is a second identity that every new endpoint must also support. The E6 material on deprecating identifiers covers the client-side of the same window.

Q148 · Scenario. "Your team's Hibernate service runs fine, but a security review flags that the application's database user has DDL and superuser rights, and that entity queries accept a client-supplied sort field. Prioritise and fix."

Reveal answer

Strong answer Two findings, different severities.

The sort field is the urgent one: if it is interpolated into a JPQL or native order by string, it is an injection vector; even through Spring Data's Sort.by(field), an arbitrary field name lets a client sort by — and thereby infer, through response ordering — columns they should not see (password_hash, another tenant's fields), and can trigger a join through a path like customer.email.

Fix today: an allow-list map from API sort names to entity properties, reject anything else with a 400, and never build query strings from request input; check every @Query for concatenation.

The privileges finding is important but scheduled: the application user needs only DML on its schema; DDL belongs to the migration job's user, which runs separately (Q134); remove superuser, and on PostgreSQL enable row-level security policies where multi-tenant tables exist (Q80), because with validate the application never needs DDL at runtime.

Verify by booting in staging with the reduced role. Also confirm the JDBC URL is not logging parameters at TRACE in production and that show-sql is off. Prevention: a CI check that the runtime datasource role cannot CREATE, and a parameterisation lint on query strings.

Land it Allow-list the sort field today, split the DDL role from the runtime role this sprint — validate means the app never needs to alter anything.

Likely follow-ups
"Show the allow-list for sort fields in code and say why a Sort.by(field) from the request is not enough."

A map from API names to entity paths: Map.of("created", "createdAt", "total", "total.amount", "customer", "customer.displayName"), and a method that resolves the request's sort parameter through it, throwing a 400 on a missing key, before constructing Sort.by(direction, resolved).

Sort.by(field) straight from the request is not enough because Spring Data validates only that the path exists on the entity, not that the client is allowed to sort by it, so passwordHash or customer.taxId is accepted, and a sort by a secret column leaks its ordering, which is an oracle for guessing values one comparison at a time.

It also allows sorting through any association, which forces a join the query never intended and can produce the row multiplication from Q97. The allow-list is ten lines and closes both.

"The security team wants the DDL split done this week, not next sprint. What is the fastest safe sequence?"

Day one: create a new role orders_app with CONNECT, USAGE on the schema, and SELECT, INSERT, UPDATE, DELETE on all tables plus USAGE on all sequences, with default privileges set so future tables get the same grants.

Day two: boot staging with the new role and validate, run the full integration suite and a traffic replay, watching for permission errors, which will appear if any code path does DDL, calls a function the role cannot execute, or truncates.

Day three: switch the migration job to the old privileged role explicitly, and the application to orders_app in production during a low-traffic window, with the previous credential ready to swap back. Day four: revoke superuser from the old role, keep DDL on it.

It is a week only because of the staging soak, which is the part not to cut.

"Where else do Hibernate applications commonly accept client input into query structure?"

Four places I audit. Dynamic filter fields on search endpoints, where a client-supplied field name becomes root.get(fieldName) in a Specification, which is the same allow-list problem as sorting. Native queries built with string concatenation for "dynamic" WHERE clauses or table names, which is direct injection.

@Query strings with SpEL expressions such as #{#entityName} that are safe, versus SpEL that interpolates a method parameter into the query text, which is not. And page size, where an unbounded size parameter is not injection but is a denial-of-service vector, so it is capped.

The fix for all of them is the same shape: request input selects from a server-side allow-list, and only values, never structure, reach the query as bound parameters.

"How do you verify the reduced role cannot do DDL, in CI, forever?"

A test in the integration suite that connects as the runtime role and attempts CREATE TABLE ci_probe (id int), asserting a permission-denied exception, and the same for ALTER TABLE orders ADD COLUMN probe int and DROP TABLE.

It runs against the Testcontainers database where the roles are created by the same migration script that creates them in production, so the grants under test are the real ones.

A second test as the migration role asserts the opposite, so a grant regression in either direction fails the build.

This is a five-minute test that makes the privilege split a property of the codebase rather than of one environment's configuration, which is what a security reviewer wants to see the next time.

Q149 · Design. "Design event sourcing for the orders aggregate on top of PostgreSQL and JPA — or argue that you would not, and what you would do instead."

Reveal answer

Strong answer I would argue against full event sourcing for orders, and design the alternative. Requirements that push toward it: a complete history, the ability to replay, and temporal queries.

What full event sourcing costs on JPA: the aggregate is no longer a row but a fold over an event stream, so the ORM's core value — dirty checking and relationships — is unused; every load replays events or hits a snapshot table; queries need separate projections maintained by handlers; and schema evolution of events (versioned payloads, upcasting) is a discipline most teams underestimate.

The design I would build instead: the state-based aggregate from this primer as the source of truth, with Envers or a hand-rolled audit table giving history and temporal reads (Q29), and an outbox-published domain event per state change (Q30) giving other services the stream they want.

That delivers 90 percent of the benefits — history, integration events, replayable projections downstream — while keeping loads as one indexed query and invariants in plain Java.

If a specific requirement demands true event sourcing — regulatory replay from events, or a domain where the events are the business (trading, betting) — I would use a purpose-built store or a dedicated event table with (aggregate_id, sequence) uniqueness for optimistic concurrency, an @Immutable event entity, batched inserts, and snapshots every N events, and keep JPA out of the read side entirely.

What I would not do: event-source everything because it sounds rigorous, then discover the read models are the whole project.

Land it State plus audit plus outbox events gives most of event sourcing's value at a fraction of its cost — reserve the full pattern for domains where the events are the product.

Likely follow-ups
"The requirement changes: regulators require replaying the order's full history from primary records. Does your alternative still hold?"

It holds if the audit table is the primary record, and that is the design decision to make explicit.

Envers or the hand-rolled audit writes a row per change in the same transaction as the change, so it is as primary as the state row, and replaying an order's history is reading its audit rows in order.

What it does not give is the ability to rebuild state from a different fold, since the audit stores state snapshots per change rather than the intent; if the regulator wants "what command was issued" rather than "what the row looked like after", the audit row must also carry the command name and its parameters, which is an extra column and a discipline at each service method.

That is a small step toward events without the full pattern. If the requirement is literally "the events are the record", then it is the event-sourced design, and I would say so.

"Under time pressure, which piece of the state-plus-audit-plus-outbox design would you cut?"

The outbox, because the audit table already gives history and the outbox exists for integration events that other services need; if no consumer exists yet, publishing can wait.

I would not cut the audit, because retrofitting history onto an aggregate that has been changing for months is impossible, and Envers is a dependency and an annotation.

I would not cut @Version, which is both a correctness guard and the sequence number the audit rows use.

When the first consumer appears, the outbox is added as a table and a poller, and the events are built from the same audit rows, so nothing is wasted.

The cut is safe because it removes a feature nobody uses yet, and the two keeps are the ones you cannot add later.

"How would optimistic concurrency work in the event table design?"

With a unique constraint on (aggregate_id, sequence).

To apply a command, the service loads the events for the aggregate, or the latest snapshot plus the events after it, folds them into state, decides the new events, and inserts them with sequence numbers continuing from the last one loaded.

If another transaction appended in the meantime, the insert collides on the unique index and fails, which is the optimistic-lock signal; the service reloads and retries. It is the same shape as @Version with the version column replaced by the sequence, and the same retry loop.

Batched inserts through a StatelessSession keep the append fast, and the @Immutable event entity keeps Hibernate from ever dirty-checking the stream. The snapshot every N events bounds the load cost; without it, an order with ten thousand events is a ten-thousand-row read per command.

"What is the concrete cost of event schema evolution that teams underestimate?"

Events are forever, and the code that reads them must understand every version ever written.

Renaming a field in an event means either rewriting history, which is forbidden, or an upcaster that translates old payloads to the current shape at read time, and every upcaster stays in the codebase as long as any old event exists, so after three years the read path runs through a chain of translations.

Removing information from an event is impossible if anything downstream needed it. Changing semantics, what "OrderShipped" means, is worse than changing shape, because no translation can fix a different meaning.

The state-based design changes a column with a migration and moves on, and the audit table's old rows simply have the old columns. Teams that have not lived through the third year of an event store do not price this in.

Q150 · Design. "Final question: a director asks you to write the three-sentence policy on 'how we use Hibernate here'. What are the sentences, and what incident does each one prevent?"

Reveal answer

Strong answer Sentence one: "Every unit of work is an explicit, short transaction on a service method, with no network I/O inside it, read-only when it does not write, and open-session-in-view off." It prevents the pool-exhaustion outages (Q18, Q36), the lazy-loading exceptions that only appear in production (Q15), and the stale merges from long-lived entities (Q126).

Sentence two: "We know the SQL: every association is lazy and fetched explicitly per query, lists return projections, every endpoint test asserts its statement count, and batching with sequence ids is on by default." It prevents the 1,200-query endpoint (Q81), the in-memory pagination (Q93), the six-hour import (Q101), and the report that serialises entities (Q98).

Sentence three: "The schema is owned by reviewed migrations run once per deploy, validated at startup, changed only in expand-and-contract steps that the previous release can survive, and every aggregate carries a version column." It prevents the concurrent-DDL deploy failures (Q117, Q128), the forty-minute lock (Q130), the rename that broke old pods (Q129), and the lost updates nobody saw (Q126, Q64).

Each sentence is short enough to put on the first page of the repository and specific enough that a pull request can be checked against it — which is the test of a policy, as opposed to a wish.

Land it Short transactions, known SQL, migrated schema — three sentences, and every incident in this drill lives under one of them.

Likely follow-ups
"The director asks which sentence you would drop if you could keep only two. Which, and what incident do you accept?"

I would drop the third sentence, about schema and versions, and I would say why: its incidents are the ones with the best safety nets already.

validate stops a bad deploy at the readiness gate, a lock is a scheduled outage that ends, and a rename mistake is loud.

The incidents under sentence one, pool exhaustion and stale merges, take the whole service down or silently corrupt data; the ones under sentence two, N+1s and in-memory pagination, are the daily latency tax and the Monday-morning surprise.

So I accept slower, louder failures in exchange for keeping the two sentences that prevent the quiet and total ones.

Then I would ask for the third sentence back the first time we plan a large-table migration, because that is when its incidents become the loud ones.

"How do you check a pull request against the three sentences in under five minutes?"

With a checklist that maps to visible things in the diff. Sentence one: is every @Transactional on a service method, does any transactional method call a client, producer, or Thread.sleep, and is readOnly present on reads.

Sentence two: does any new association lack fetch = LAZY, does any list endpoint return an entity, does every new endpoint test include a statement-count assertion, and is any Pageable method carrying an entity graph with a collection.

Sentence three: does an entity change come with a migration, does the migration follow expand-first, and is there a @Version on any new aggregate. Most of these are also ArchUnit or lint rules, so the human check is the residue.

A five-minute review that asks those questions catches what the tooling cannot yet phrase.

"What would you add as a fourth sentence for a team that runs on multiple nodes with caching?"

"Nothing is cached at the entity layer unless it is immutable, and every read model cache is invalidated from the write path after commit.

" It prevents the two-pods-two-prices incident from Q107, the stale query cache from Q108, and the cache that never learns about writes made outside Hibernate from Q115.

It also covers the Spring @Cacheable on a method returning an entity, which is a cross-request leak waiting to happen.

The reason it is a fourth sentence rather than part of the first three is that caching is a decision a team can defer entirely, and many should; the sentence exists so that when someone reaches for a cache, the two conditions are already written down. It is the sentence for the second year of the service.

"What makes a policy sentence checkable rather than aspirational, in your experience?"

Three properties. It names an observable: a setting, an annotation, a test, a number, so a reviewer can point at a line and say yes or no. It names the failure it prevents, so exceptions are argued against a concrete cost rather than a preference.

And it is enforced by something other than memory: an ArchUnit test, a lint, a CI job, so the policy holds on the day nobody is paying attention. "We write good SQL" fails all three; "every endpoint test asserts its statement count" passes all three.

The director's request for three sentences is a good constraint precisely because it forces choosing the observables that matter most, and the drill questions behind each sentence are the evidence that they do.

11 · RecapWhat You Can Do Now

  • You can say what the persistence context is — an identity map with snapshots and an action queue — and predict, line by line, when Hibernate sends each statement
  • You can explain what save() does with the object you pass it, and why merge returns a different object than the one you gave it
  • You can read a mapping as SQL: which side writes the foreign key, what a bag rewrite costs, why IDENTITY kills batching, and what cascade and orphan removal each delete
  • You can choose between optimistic and pessimistic locking from the conflict rate, write the retry in the right place, and design a skip-locked job queue
  • You can find an N+1 from the statistics, pick join fetch, batch fetch, subselect or a projection by access pattern, and recognise the in-memory pagination trap
  • You can make a five-million-row import run in minutes with sequence ids, JDBC batching, and a stateless session, and keep a batch job's heap flat
  • You can say when the second-level cache helps, when it lies across nodes, and what to cache instead
  • You can ship a column rename across a rolling deploy in expand-and-contract steps, and explain why ddl-auto=update never runs in production
🧠 Flex your memory

Close the page and write down, from memory: the four entity states with the call that causes each transition, and the three events that trigger a flush under AUTO mode — then the four fixes for an N+1 in the order you would reach for them. Then reach back to Chapter E8's isolation chapter: at which isolation level does PostgreSQL abort a writer whose row changed since its snapshot, and why does that not make @Version redundant for a load-edit-save flow that spans two HTTP requests?