Hibernate and JPA interview questions and answers

Hibernate and JPA interview questions check whether you know what the ORM does behind your repository calls: entity states and the persistence context, dirty checking at flush, lazy versus eager loading, the N+1 query problem, fetch joins, caching levels, transactions and optimistic locking. Senior rounds hand you a slow endpoint or a LazyInitializationException and ask for the cause. The best answers always say which SQL Hibernate will run.

By Published 8 min read

How Hibernate questions show up

Hibernate questions appear in nearly every Java backend interview, usually in the same round as Spring Boot. Junior candidates get definitions: JPA versus Hibernate, entity annotations, the difference between persist and merge. Mid-level and senior candidates get performance and correctness: why an endpoint issues 300 queries, why a lazy collection throws outside a transaction, how two users editing the same record are handled. Some teams also paste a mapping and ask what tables and SQL it produces.

  1. Concept screenJPA versus Hibernate, entity states, first-level cache, fetch types, cascade types.
  2. Code review or live codingRead an entity and a repository method, predict the queries, fix an N+1 or a mapping bug.
  3. Design and production roundConcurrency control, batching a large import, caching, schema migrations and when to drop down to SQL.

Fundamentals: JPA, entities and the persistence context

Hibernate and JPA basics
QuestionWhat it testsWhat a strong answer shows
What is the difference between JPA and Hibernate?Spec versus implementationJPA (now Jakarta Persistence, package jakarta.persistence) defines the annotations and the EntityManager API. Hibernate ORM implements it and adds its own features, such as extra fetch strategies and the Session API.
What are the entity states?LifecycleTransient (new, not tracked), managed (in a persistence context), detached (was managed, context closed or cleared) and removed (scheduled for deletion at flush).
What is the persistence context?Core mechanismThe set of managed entities for one EntityManager, usually one per transaction. It guarantees one Java object per database row and is the first-level cache.
What is dirty checking?Change trackingAt flush, Hibernate compares managed entities with the snapshot taken when they were loaded and issues UPDATEs for changes. Modifying a managed entity inside a transaction is enough; no save call is needed.
When does Hibernate flush?Flush modesBefore commit, before a query that might read affected tables (AUTO mode), and when you call flush(). COMMIT mode skips the pre-query flush.
persist versus merge?API semanticspersist makes a new instance managed. merge copies the state of a detached object onto a managed instance and returns that instance; the argument stays detached.
find versus getReference?Proxiesfind hits the cache or the database and returns null if missing. getReference may return an uninitialized proxy without a query, failing only when you access its state, which is useful for setting foreign keys.
SessionFactory versus Session?Thread safetyThe SessionFactory (EntityManagerFactory) is expensive, thread-safe and created once. A Session (EntityManager) is cheap, not thread-safe and short-lived.
Which side owns a bidirectional relationship?MappingThe side without mappedBy, normally the @ManyToOne holding the foreign key. Changes only on the inverse side are not written; keep both sides in sync with helper methods.
What do cascade and orphanRemoval do?Object graphsCascade passes operations such as persist or remove from parent to children. orphanRemoval deletes a child that is removed from the parent's collection.
What are the inheritance strategies?Mapping hierarchiesSINGLE_TABLE (one table with a discriminator, fastest, nullable columns), JOINED (normalized, joins on read), TABLE_PER_CLASS (union queries). @MappedSuperclass shares fields without a queryable parent.
Hibernate and JPA basics. Scroll sideways on a small screen.

Lazy versus eager loading and the N+1 problem

This is the topic interviewers spend the most time on. JPA's defaults are part of the trap: @ManyToOne and @OneToOne are EAGER by default, while @OneToMany and @ManyToMany are LAZY. A common team rule is to declare every association LAZY and decide fetching per query.

  • What is the N+1 select problem? One query loads N parent rows, then accessing a lazy association on each parent fires one more query per parent. Fifty orders with lazy customers become 51 queries.
  • Does EAGER fix N+1? No. EAGER on a to-one association loaded through a JPQL query still triggers a separate select per row unless the query fetches it, and it loads the data everywhere, even where unused.
  • How do you detect N+1? Log SQL in tests, enable Hibernate statistics, or assert the query count in an integration test so a regression fails the build.
  • What is a fetch join? JOIN FETCH in JPQL loads the association in the same SQL statement and initializes it, so later access does not query again.
  • What is an entity graph? A named or ad hoc description of which attributes to load, applied per query, for example with @EntityGraph on a Spring Data method. It keeps fetching decisions out of the mapping.
  • What is batch fetching? With @BatchSize or hibernate.default_batch_fetch_size, Hibernate loads lazy proxies or collections for many parents with one IN query, turning N+1 into roughly N divided by the batch size plus one.
  • Why can't you fetch two List collections at once? Joining two bags multiplies rows, and Hibernate cannot tell duplicates apart, so it throws MultipleBagFetchException. Fetch one per query, use Set where it makes sense, or use batch fetching for the second.
  • What goes wrong with JOIN FETCH on a collection plus pagination? The SQL row limit would cut a parent's children, so Hibernate loads everything and paginates in memory, logging a warning. Page the parent IDs first, then fetch those parents with their collections.
  • What is LazyInitializationException? Accessing an uninitialized lazy association after the persistence context closed. Fix it by fetching what the use case needs inside the transaction, not by switching to EAGER.
  • What is open session in view, and why do many teams turn it off? It keeps the persistence context open through view rendering, so lazy loading works anywhere, but it hides N+1 queries and holds a connection for the whole request. Spring Boot enables it by default and logs a warning about it.
@Entity
public class PurchaseOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)   // override the EAGER default
    private Customer customer;

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

    @Version
    private long version;

    private String status;
}

public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {

    // One SQL statement: orders joined with their customers
    @Query("select o from PurchaseOrder o join fetch o.customer where o.status = :status")
    List<PurchaseOrder> findWithCustomer(@Param("status") String status);

    // Same idea, declared as an entity graph
    @EntityGraph(attributePaths = {"customer", "lines"})
    List<PurchaseOrder> findByStatus(String status);
}
An order with a lazy customer and lazy lines, and two ways to load what a list screen needs. Compiled with javac against stand-in annotations for syntax only; not run with Hibernate.

For read-only screens, a DTO projection is often better than entities: select new com.shop.OrderRow(o.id, c.name, o.status) from PurchaseOrder o join o.customer c loads exactly three columns, creates no managed objects and needs no dirty checking.

Caching: first level, second level and query cache

Cache questions
QuestionWhat it testsWhat a strong answer shows
What is the first-level cache?Persistence contextAlways on, scoped to one EntityManager. Loading the same ID twice in one transaction returns the same object without a second query.
What is the second-level cache?Shared cacheOptional, scoped to the SessionFactory and shared across sessions. You enable it per entity and plug in a provider, typically through JCache with Ehcache, Infinispan or similar.
Which concurrency strategies exist?Cache consistencyREAD_ONLY for data that never changes, NONSTRICT_READ_WRITE for rare updates with brief staleness, READ_WRITE with soft locks for stronger consistency, TRANSACTIONAL with a JTA-capable provider.
What does the query cache store?Query resultsThe IDs returned by a query for given parameters, not the entities. It is invalidated whenever any of its tables changes, so it suits rarely updated reference data.
When does the second-level cache hurt?JudgmentOn write-heavy data, in clusters without a distributed or invalidating provider, and when bulk JPQL updates or other applications change the tables behind its back.
Cache questions. Scroll sideways on a small screen.

Transactions, locking and concurrency

  • How does optimistic locking work in JPA? A @Version column is checked in the WHERE clause of every UPDATE and incremented. If another transaction changed the row first, zero rows match and Hibernate throws an OptimisticLockException.
  • When would you use pessimistic locking instead? For hot rows with frequent conflicts, such as a stock counter. LockModeType.PESSIMISTIC_WRITE issues a SELECT ... FOR UPDATE on most databases; keep the transaction short.
  • Why does @Transactional on a private method or a self-call do nothing in Spring? Spring applies it through a proxy, so only calls that come through the proxy from outside the bean start a transaction.
  • What does readOnly = true change? Hibernate can skip dirty checking snapshots and flushing for that session, and some drivers route the connection to a replica. It is a hint, not a security boundary.
  • Which exceptions roll back a Spring transaction by default? Unchecked exceptions and errors. Checked exceptions commit unless you configure rollbackFor.
  • How do you handle a long user edit across two requests? Load in one transaction, send the version to the client, and on save merge with the original version so the @Version check catches concurrent changes.

IDs, batching and performance

Senior performance questions
QuestionWhat it testsWhat a strong answer shows
IDENTITY or SEQUENCE?Insert batchingWith IDENTITY the ID is known only after the INSERT runs, so Hibernate executes inserts immediately and cannot batch them. SEQUENCE with a pooled allocationSize (50 by default in JPA) fetches IDs in blocks and keeps batching.
How do you import a million rows with Hibernate?Batch processingSet hibernate.jdbc.batch_size, order inserts, flush and clear the persistence context every batch so memory stays flat, or use a StatelessSession. For huge loads, plain JDBC or the database's bulk loader.
Why does a bulk JPQL UPDATE leave stale entities?Bypassing the contextBulk statements go straight to the database; managed entities in memory are not updated. Clear the context afterwards or run bulk updates in a separate transaction.
How should equals and hashCode work for entities?IdentityDo not rely on a generated ID that is null before persist. Use a natural business key, or compare by ID when it is non-null and return a constant hashCode per class.
Should hibernate.hbm2ddl.auto be update in production?Schema managementNo. Use validate at most, and manage schema changes with migration tools such as Flyway or Liquibase so they are reviewed and versioned.
JPQL, Criteria or native SQL?Query choiceJPQL for most entity queries, Criteria for dynamic filters built in code, native SQL for database-specific features such as window functions or JSON operators.
Senior performance questions. Scroll sideways on a small screen.

Scenario questions

Hibernate problems interviewers describe
ScenarioLikely causeWhat you would do
An order list endpoint runs 201 queries for 100 orders.N+1 on two associationsTurn on SQL logging, then add a fetch join or entity graph for one association and batch fetching for the other.
LazyInitializationException in a JSON serializer.Entity leaving the transactionMap to DTOs inside the service layer, or fetch the needed associations in the query.
Saving a parent duplicates its children.merge on a detached graph with new childrenCheck cascade settings and whether children have IDs; prefer loading the parent and modifying it.
Memory climbs during a nightly import until the job crashes.Persistence context growsflush() and clear() every batch, or a StatelessSession.
Users report their edits silently overwritten.No concurrency controlAdd @Version and handle OptimisticLockException with a clear retry or merge message.
Hibernate problems interviewers describe. Scroll sideways on a small screen.

Fictional example

Answering "This endpoint is slow. Here is the repository method."
Interviewer
GET /orders returns 50 orders with customer name and line count. It takes two seconds. The repository just calls findAll with a page request. What is going on?
Candidate
My first guess is N+1. findAll loads the orders in one query, then the mapper touches order.getCustomer().getName() and order.getLines().size(), and each lazy access fires its own select, so 50 orders can mean about 100 extra queries. I would confirm by enabling SQL logging or Hibernate statistics for one request. For the fix, this screen only needs three fields, so I would write a DTO projection: select the order ID, the customer name and a count of lines, with a join and a group by. That is one query, no managed entities and no dirty checking. If the service needs real entities, I would fetch the customer with an entity graph and set a default batch fetch size so the lines load in a few IN queries, since fetch-joining a collection with paging would make Hibernate paginate in memory. Then I would add a test that asserts the query count so this does not come back.

Ten-day Hibernate practice plan

  • Days 1 and 2: build a small Spring Boot app with three related entities, turn on SQL logging, and predict every statement before you run each repository call.
  • Days 3 and 4: reproduce N+1, then fix it four ways: fetch join, entity graph, batch fetching and a DTO projection. Compare query counts.
  • Days 5 and 6: trigger LazyInitializationException, MultipleBagFetchException and the in-memory pagination warning on purpose and explain each.
  • Days 7 and 8: add @Version, run two concurrent updates in a test and handle the exception; then try PESSIMISTIC_WRITE and read the generated SQL.
  • Days 9 and 10: import 100,000 rows with IDENTITY versus SEQUENCE and batching on, and rehearse the scenario table out loud.

Hibernate questions usually lead into the database underneath. PostgreSQL interview questions and MySQL interview questions cover the locking and index behavior your ORM inherits. If the same service exposes GraphQL, the N+1 problem returns at the resolver level: see GraphQL interview questions. Broader backend topics are in backend developer interview questions.

ORM answers are a chain: mapping, then the SQL it produces, then the fix. Natively, an AI interview assistant for Mac and Windows, transcribes a mock Java round on your computer so you can check afterwards whether you named the queries before proposing a change. In practice it can read an entity class or a stack trace from a screenshot and suggest what to look at, and with Pro or the free trial it can use the résumé and job description you add. Your notes and the transcript are kept for review.

Questions people ask

What Hibernate questions are asked in interviews?

Expect JPA versus Hibernate, entity states, the persistence context and dirty checking, lazy versus eager loading, the N+1 problem and its fixes, first and second level caching, @Version optimistic locking, ID generation and batch inserts.

What is the N+1 problem in Hibernate?

One query loads a list of entities, then touching a lazy association on each one fires another query per entity. Fix it with a JOIN FETCH, an entity graph, batch fetching or a DTO projection, chosen per use case.

What is the difference between the first-level and second-level cache in Hibernate?

The first-level cache is the persistence context: always on and scoped to one EntityManager. The second-level cache is optional, shared across sessions through the SessionFactory and enabled per entity with a cache provider.

What is the difference between JPA and Hibernate?

JPA, now Jakarta Persistence, is a specification of annotations and the EntityManager API. Hibernate ORM is an implementation of that specification that also adds its own APIs and features.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP