skip to content

Persistence Context & Session

The engine room of Hibernate: entity states, the first-level cache, dirty checking, and flushing — where the ORM decides what SQL to run and when. Interviewers drill here because candidates who understand the persistence context can predict Hibernate; everyone else just reacts to it.

part ofHibernateoverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

A batch job iterates a million rows through a single Hibernate Session and the JVM heap climbs until it runs out of memory, even though each row is processed and then never referenced again. Why does the session grow, and what techniques keep memory flat?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The persistence context holds a strong reference to every entity it loads, plus a snapshot copy of its loaded values for dirty checking — roughly double per entity, never released until evict, clear or close. Fix it with periodic flush()+clear(), read-only or stateless access, and paged or scrolled reads.

open as a page

A detached order object with its collection of line items arrives back from a client and the code calls merge() on the order. What determines whether the child rows are written, and what commonly goes wrong with that collection?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Children are merged only where the association declares CascadeType.MERGE or ALL; otherwise new children fail at flush as transient references. With orphanRemoval, any child missing from the incoming collection is deleted — so a partially populated collection silently destroys rows.

open as a page

In plain Hibernate, what is the difference between SessionFactory.openSession() and SessionFactory.getCurrentSession(), and what determines the scope and lifetime of a "current" session?

level: seniorimportance: should knowfreq 34%

basics

~20 s

openSession() always creates a new session that you must close yourself. getCurrentSession() returns the session bound to the current context — thread or JTA transaction, per hibernate.current_session_context_class — creating it on first call and closing it automatically at transaction end.

open as a page

You need a durable audit trail of every change to a set of entities: who changed what, with old and new values. Compare building it on JPA lifecycle callbacks, on Hibernate Envers, and on database triggers.

level: principalimportance: should knowfreq 28%

basics

~20 s

Callbacks are simple but blind to old values, bulk JPQL, native SQL and outside writers. Envers versions entities automatically with revision metadata and a query API, but still only sees ORM writes and grows tables. Triggers catch every write including out-of-band ones, but lose application context and are database-specific.

open as a page

You inherit a large service that renders entity graphs and depends on the persistence context staying open until the response is written. Design the fetching boundary you would move it to, and how you would sequence the migration without a big-bang change.

level: principalimportance: should knowfreq 33%

basics

~10 s

Move to transaction-per-request-handler: the service fetches exactly what the response needs and returns immutable projections, so nothing lazy survives into rendering. Migrate endpoint by endpoint behind statement-count tests, then disable the request-scoped session last.

open as a page

When would you deliberately write code against Hibernate's native API instead of staying on the portable JPA API, and how do you stop that decision from spreading uncontrolled through a codebase?

level: principalimportance: should knowfreq 28%

basics

~20 s

Go native when JPA has no equivalent and the workaround is worse: StatelessSession bulk work, multiLoad, natural-id lookup, @Filter, custom types, Hibernate lock modes, statistics. Contain it behind narrow, documented seams rather than scattering unwrap() calls.

open as a page

Hibernate can be configured with build-time bytecode enhancement so entities track their own modifications instead of being compared against snapshots at flush. What changes at runtime when you enable it, and when is that trade actually worth making?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Enhancement instruments entity classes so each field write records the attribute name in a tracker on the object. At flush Hibernate asks the entity which attributes are dirty instead of walking snapshots, making flush proportional to what changed rather than what was loaded. Worth it only for large persistence contexts or wide entities; mutating a value object in place can go undetected.

open as a page

What exactly does EntityManager.contains(object) return true for? Explain why an object holding the same primary key as a row currently tracked by the persistence context can still make that method return false.

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

It returns true only when that exact instance is managed by the current persistence context. It is reference-based, not id-based, so a detached copy carrying the same id returns false even while a different managed instance of the same row is tracked.

open as a page

In an application where the persistence context stays open until the HTTP response has been rendered, code running during rendering modifies a managed entity after the service transaction has already committed. What happens to that modification, and why is either possible outcome dangerous?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Usually nothing: no transaction commits afterwards, so the change is discarded silently when the session closes. If automatic flushing is left enabled, a query during rendering can auto-flush it — writing outside any transaction, in auto-commit, with no rollback possible.

open as a page

For an edit that spans several requests — a multi-step wizard, or a form a user keeps open for minutes — how would you decide between carrying a detached object graph across the steps, holding an extended persistence context, and re-reading fresh state each step while applying a recorded change set? What does each choice cost, and what do you owe the user when a conflict is detected?

level: principalimportance: nice to knowfreq 24%

basics

~20 s

All three are ways to hold an application-level transaction across user think-time. Detached graphs are cheap but stale and destructive on merge; an extended persistence context keeps identity and dirty checking at the cost of server memory and pinned state; a change set re-read each step is the most robust. Whichever you pick, carry a version token and surface conflicts to the user rather than silently resolving them.

open as a page

showing 31–40 of 40