Home › Blog › Hibernate Interview Questions (2026): 30 Questions on Sessions, Fetching, N+1 and Caching

Hibernate Interview Questions (2026): 30 Questions on Sessions, Fetching, N+1 and Caching

Hibernate interview questions are mostly about the persistence context: which objects Hibernate is tracking, when it actually sends SQL, and how lazy loading turns into the N+1 problem. Get those three right and caching, locking and batching questions follow.

Hibernate interview questions are mostly about the persistence context: which objects Hibernate is tracking, when it actually sends SQL, and how lazy loading turns into the N+1 problem. Get those three right and caching, locking and batching questions follow. As of November 17, 2026, hibernate.org lists 7.4 as the latest stable series (7.4.16.Final, released November 15, 2026) and 8.0 in development (8.0.0.CR1, Jakarta Persistence 4.0). Hibernate 7 requires Java 17, implements Jakarta Persistence 3.2 and removed the old Session methods save, update, saveOrUpdate, load and delete.

Below are 30 questions by level, five debugging scenarios and how Java backend interviews test this. Core language ground is in Java interview questions, and the framework most teams run Hibernate inside is covered in Spring Boot interview questions.

Hibernate interview questions: fundamentals (1–10)

  1. What is Hibernate, and how does it relate to JPA? Hibernate is an object-relational mapper. Jakarta Persistence (formerly JPA) is the specification: EntityManager, mapping annotations, JPQL. Hibernate implements it and adds native features such as Session, filters and StatelessSession. Spring Data JPA builds repositories on top, with Hibernate as Spring Boot's default provider.
  2. SessionFactory versus Session? The SessionFactory (EntityManagerFactory) is heavyweight, thread-safe and built once per database at startup; it holds mappings and the second-level cache. A Session (EntityManager) is cheap, not thread-safe and lives for one unit of work.
  3. What are the entity states? Transient (new, not associated), managed (in a persistence context, changes tracked), detached (was managed, context closed) and removed (scheduled for deletion at flush).
  4. What is the persistence context? The first-level cache: an identity map per session. Loading the same ID twice returns the same instance without a second query. It is always on and ends with the session.
  5. What is dirty checking? At flush, Hibernate compares each managed entity with the snapshot taken when it was loaded and issues UPDATEs for changes. Inside a transaction you do not call save after changing a managed entity.
  6. When does Hibernate flush? With the default FlushMode.AUTO: before commit, before a query whose results pending changes could affect, and on flush(). Flushing sends SQL; it does not commit.
  7. persist versus merge? persist makes a transient object managed and inserts it at flush. merge copies a detached object's state onto a managed instance and returns that instance; the argument stays detached. Hibernate 7 removed save, update and saveOrUpdate in favour of these.
  8. find versus getReference? find returns the entity, from cache or database, or null. getReference returns a proxy without SQL and throws when accessed if the row is missing; it is useful for setting a foreign key. Hibernate 7 removed load (use getReference) and deprecated get (use find).
  9. What are the default fetch types? Per JPA, @ManyToOne and @OneToOne are EAGER; @OneToMany and @ManyToMany are LAZY. Common advice is to mark to-one associations LAZY and fetch per query.
  10. Which ID generation strategy? SEQUENCE with a pooled allocation size where the database supports it; IDENTITY uses auto-increment but inserts immediately and disables JDBC insert batching; TABLE is portable but slow; UUIDs avoid round trips but make larger indexes.

Intermediate Hibernate questions (11–20)

  1. What is the N+1 problem? One query loads N parents, then touching each lazy collection fires one more query each. Detect it with SQL logging, Hibernate statistics or a test that asserts query counts. Fix with join fetch, an entity graph, batch fetching (@BatchSize or hibernate.default_batch_fetch_size) or a DTO query.
  2. JOIN FETCH or an entity graph? select o from Order o join fetch o.items where o.id = :id fetches inside the query. An entity graph (@NamedEntityGraph, or @EntityGraph in Spring Data) describes the fetch plan separately. Fetching two List collections at once throws MultipleBagFetchException; use a Set or two queries.
  3. What causes LazyInitializationException? Touching a lazy association after its session has closed, often while serializing an entity to JSON. Fetch what the use case needs inside the transaction, or return DTOs. Keeping sessions open longer hides the problem rather than fixing it.
  4. First-level, second-level and query cache? The first-level cache is per session and always on. The second-level cache is shared across sessions, opt-in per entity (@Cacheable plus a concurrency strategy) and needs a provider through JCache. The query cache stores result IDs and is invalidated whenever a queried table changes, so it only helps rarely changing data.
  5. Cascades and orphanRemoval? Cascade types (PERSIST, MERGE, REMOVE, ALL and others) propagate operations from parent to child. orphanRemoval = true deletes a child removed from the collection. Never cascade REMOVE to shared entities or across @ManyToMany.
  6. What is the owning side of a relationship? The side holding the foreign key, usually @ManyToOne. The other side declares mappedBy and is ignored when writing. Keep both sides in sync with helper methods such as addItem() that also set item.setOrder(this).
  7. How does optimistic locking work? Add a @Version field. Updates run ... WHERE id = ? AND version = ?; zero rows updated raises OptimisticLockException. Use it for low-contention data and retry or surface the conflict.
  8. When do you use pessimistic locking? For a hot row where conflicts are frequent, such as stock counts. LockModeType.PESSIMISTIC_WRITE issues a database-specific SELECT ... FOR UPDATE. Keep the transaction short and set a lock timeout.
  9. HQL, Criteria or native SQL? HQL and JPQL are entity-oriented query strings; the Criteria API builds type-safe dynamic queries; native SQL reaches database-specific features. Bind parameters (:name) every time to prevent SQL injection.
  10. What inheritance strategies exist? SINGLE_TABLE (one table with a discriminator, fastest, nullable columns), JOINED (normalized, joins on read) and TABLE_PER_CLASS (one table per concrete class, unions for polymorphic queries). @MappedSuperclass shares fields without polymorphic queries.

Experienced and senior Hibernate questions (21–30)

  1. How do you speed up bulk inserts? Set hibernate.jdbc.batch_size, enable hibernate.order_inserts, use SEQUENCE IDs, and flush() and clear() every batch to keep the persistence context small. For very large loads, use StatelessSession or plain JDBC.
  2. What is StatelessSession? A session with no persistence context, dirty checking, cascades or first-level cache. Each call becomes SQL directly, which suits bulk jobs and streaming reads.
  3. How should entities implement equals and hashCode? Use a stable business key, or the ID with care for transient instances (equality only when the ID is non-null and a constant hashCode). Avoid generated equals that touches lazy associations or changes once the ID is assigned.
  4. What do JPQL bulk updates bypass? update Product p set p.price = p.price * 1.1 where p.category = :c runs directly in the database, skipping the persistence context, lifecycle callbacks and cascades. Managed entities become stale, so clear the context afterwards.
  5. Why use DTO projections? For read models: select new com.acme.OrderSummary(o.id, o.total) from Order o (records work well) fetches only the needed columns with no tracking or lazy loading.
  6. Should Open Session in View be on? Spring Boot enables it by default and logs a warning. It avoids LazyInitializationException in views but hides N+1 queries and holds connections longer. Many teams set spring.jpa.open-in-view=false and fetch explicitly.
  7. How do you diagnose slow Hibernate code? Log SQL with bind values, count queries per request, enable statistics, look for N+1 queries and very large persistence contexts, then check the database plan for each slow statement.
  8. What changed in Hibernate 6 and 7? Hibernate 6 moved to the jakarta.persistence namespace and rewrote the query engine. Hibernate 7.0 requires Java 17, implements Jakarta Persistence 3.2, moved to the Apache License and removed legacy Session methods. Criteria queries no longer treat a path implicitly as a subtype.
  9. How do you implement multi-tenancy? Database per tenant, schema per tenant, or a discriminator column. Hibernate resolves the current tenant with CurrentTenantIdentifierResolver, and @TenantId marks the discriminator attribute.
  10. How do you do soft deletes? Hibernate 6.4 added @SoftDelete, which turns deletes into updates of a flag and filters deleted rows from queries. The older approach combines @SQLDelete with a restriction annotation. Index the flag.

Hibernate scenario and troubleshooting questions

A page showing 200 orders runs 201 queries. N+1: the list query, then one per order's lazy collection. Fetch the collection with join fetch or an entity graph, or set a batch fetch size, then add a test that asserts the query count.

LazyInitializationException appears in the REST layer. The controller serializes an entity after the transaction ended. Map to DTOs in the service layer with the associations the endpoint needs already fetched.

An update is never saved. Typical causes: the entity is detached and the instance returned by merge was ignored; the change was made only on the mappedBy side; there was no transaction; or the transaction was read-only.

A batch job runs out of memory after a million rows. The persistence context holds every loaded entity. Flush and clear every few hundred rows, stream with a fetch size, or switch to StatelessSession.

OptimisticLockException spikes under load. Many writers hit the same rows. Retry with backoff, shorten transactions, split the hot aggregate, or use a pessimistic lock on that one path.

How Hibernate interviews test this

FormatWhat it usually looks likeHow to prepare
Concept Q&AEntity states, persistence context, fetch types, caching levelsExplain each with one code line
Code review"What is wrong with this repository method?" (usually N+1 or a detached update)Practice spotting N+1 and owning-side mistakes
Spring backend roundHibernate inside Spring Boot: transactions, open-in-view, Spring DataKnow where transactions start and end
Senior designBatch processing, locking strategy, caching, migrationsBring one performance fix with before and after query counts

Expect SQL follow-ups on indexes and joins; SQL interview questions covers that side, and lambdas used with repositories are in Java 8 interview questions.

Where CoPilot Interview fits

CoPilot Interview is an AI interview assistant. Its free AI mock interview builds Hibernate, JPA and Java backend questions from your résumé and the job description, reads them aloud and scores each spoken answer out of 10, which is a fast way to find the answers above that you know but cannot yet explain cleanly under pressure. The browser demo has 145 practice questions in 10 tracks, scores typed answers out of 10 and needs no signup. The free plan gives 15 minutes a day of live help in sessions of up to 15 minutes, with AI mock interviews included. Paid plans are Standard at $24.99 a month and Pro at $39.99 a month, in the desktop app for Windows 10/11 and macOS 12 or later.

Use it to practice. Online assessments, proctored tests, take-home tasks with rules and AI-led rounds forbid outside help, so prepare for those instead of bringing a tool. For any live interview, follow your employer's rules.

Disclosure: CoPilot Interview is our product, so weigh what we say about it accordingly.

Frequently asked questions

What are the most common Hibernate interview questions?

Entity states, the persistence context and dirty checking, lazy versus eager fetching, the N+1 problem, LazyInitializationException, first- and second-level caching, optimistic locking and persist versus merge.

What is the difference between JPA and Hibernate?

Jakarta Persistence (JPA) is a specification of interfaces and annotations; Hibernate is an implementation of it with extra native features.

What is the difference between get() and load() in Hibernate?

Historically, get hit the database and returned null if missing, while load returned a proxy. In Hibernate 7, load was removed in favour of getReference, and get is deprecated in favour of the JPA-standard find.

What is the latest version of Hibernate?

On November 17, 2026, hibernate.org listed 7.4 as the latest stable series (7.4.16.Final, November 15, 2026) and 8.0.0.CR1 as the development release for Jakarta Persistence 4.0.

How do I explain the N+1 problem in an interview?

Say what triggers it (a lazy association touched in a loop), how you detect it (SQL log or query-count test), and two fixes (join fetch or batch fetching), ideally with a real before-and-after query count.

Practice this interview before the real one

The AI mock interview builds questions from your resume and the job description, reads them aloud and scores each spoken answer out of 10. Included on the free plan.

Start a mock interview