Hibernate and JPA Interview Questions and Answers
Last updated 2026-11-19
Hibernate questions are really questions about the persistence context: what it caches, when it flushes, which objects it tracks and why a lazy association throws an exception outside a transaction. Interviewers also ask about the performance traps that cause most production problems, such as the N+1 select problem, unbounded eager fetching and entity equality.
This page answers for Jakarta Persistence 3.1 with Hibernate 6, as used in Spring Boot 3, so imports are from jakarta.persistence. The framework side is covered in the Spring Boot interview questions, SQL fundamentals in DBMS interview questions, and the language side in how to crack a Java interview.
| Versions | Jakarta Persistence 3.1, Hibernate 6.x, Spring Data JPA 3 |
|---|---|
| Core topics | Entity lifecycle, fetching, N+1, cascades, locking, caching, batching |
| Questions here | 17 |
The persistence context in one paragraph
An EntityManager, or Hibernate Session, holds a first-level cache of the entities it has loaded, guarantees one instance per row within the context and tracks changes. At flush time, which happens before a query that might be affected and at commit, Hibernate compares each managed entity with its loaded snapshot and issues UPDATE statements for differences. This dirty checking is why you rarely call save on a managed entity, and why detached objects need merge.
Defaults you should know
- ManyToOne and OneToOne default to EAGER, while OneToMany and ManyToMany default to LAZY.
- Enum fields map to ordinal numbers by default, so set EnumType.STRING.
- IDENTITY generation disables JDBC insert batching, whereas SEQUENCE allows it.
- Spring Boot enables open-in-view by default, which keeps a session open during view rendering and can hide lazy loading problems.
- Hibernate 6 uses jakarta packages and generates SQL from a rewritten query model.
Hibernate and JPA Interview Questions and Answers: questions with worked answers
1 What is the difference between JPA and Hibernate?
easyJPA, now Jakarta Persistence, is a specification: annotations, the EntityManager API and JPQL. Hibernate is the most widely used implementation, and adds features beyond the spec, such as the Session API, filters and extra caching options. Spring Data JPA is a further layer that generates repository implementations on top of a JPA provider, usually Hibernate.
2 Explain the entity states: transient, managed, detached and removed.
easyA transient entity is a new object that is not associated with any session and has no row. Calling persist makes it managed, so the persistence context tracks it and flushes changes. After the session closes, or after detach or clear, it becomes detached and changes are no longer tracked, but merge can copy its state onto a managed instance. remove schedules deletion of a managed entity.
3 Explain persist, merge, save and getReference.
mediumpersist makes a new entity managed and may assign its ID, and it must not be used on a detached entity. merge copies the state of a detached or transient object onto a managed instance and returns that instance, so you must use the returned object. Spring Data save calls persist for new entities, and merge otherwise. getReference returns a lazy proxy without hitting the database, which is enough to set a foreign key.
javaPost post = new Post("title"); em.persist(post); // INSERT at flush Author ref = em.getReference(Author.class, 7L); // no SELECT post.setAuthor(ref);4 What is dirty checking and when is the flush?
mediumOn flush Hibernate compares each managed entity to the snapshot taken at load and writes UPDATE statements for changed fields, so you do not call save for managed objects. Flush happens at commit, before a query whose tables have pending changes in AUTO mode, and when you call flush explicitly. This is why modifying an entity inside a read-only transaction may silently not persist.
java@Transactional public void rename(long id, String name) { Product p = em.find(Product.class, id); p.setName(name); // UPDATE is issued at commit, no save() call }5 Lazy versus eager loading, and what causes LazyInitializationException?
mediumLAZY defers loading an association until it is accessed, using a proxy or a lazy collection. EAGER loads it with the owner. LazyInitializationException occurs when you touch an uninitialised proxy after the session has closed, typically in a controller after the transactional service returned. Fix it by fetching what you need inside the transaction using a fetch join, entity graph or DTO projection, not by switching everything to EAGER.
6 What is the N+1 select problem and how do you fix it?
mediumLoading N parents and then accessing a lazy association on each issues one extra query per parent. Fix it with a JOIN FETCH query, an @EntityGraph, a DTO projection that selects only needed columns, or batch fetching with @BatchSize or hibernate.default_batch_fetch_size, which loads associations for many parents with one IN query. Fetch-join only one collection at a time to avoid MultipleBagFetchException and cartesian products.
java@Query("select distinct o from Order o join fetch o.items where o.customer.id = :cid") List<Order> findWithItems(@Param("cid") Long cid);7 What does mappedBy mean, and which side owns the relationship?
mediumIn a bidirectional association, the owning side is the one that holds the foreign key, such as the @ManyToOne field, and only changes to it are written to the database. The inverse side uses mappedBy to refer to the owning field. Updating only the inverse collection does nothing, so use helper methods that set both sides.
java@Entity class Order { @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) private List<OrderItem> items = new ArrayList<>(); public void addItem(OrderItem i) { items.add(i); i.setOrder(this); } } @Entity class OrderItem { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_id") private Order order; }8 What do cascade types and orphanRemoval do?
mediumCascade propagates an operation from a parent to its associated entities: PERSIST, MERGE, REMOVE, REFRESH, DETACH or ALL. orphanRemoval deletes a child row when it is removed from the parent collection. Use them only for true ownership such as an order and its items. Never cascade REMOVE from a child to a shared parent, such as deleting a user when deleting one of many posts.
9 JPQL versus native SQL versus Criteria API?
mediumJPQL queries entities and their fields, so it is portable and typed to the model. Native SQL uses database features that JPQL lacks, such as window functions, but returns arrays or needs result mapping and bypasses some persistence context behaviour. The Criteria API builds queries programmatically for dynamic filters. Spring Data derived queries and Specifications cover many dynamic cases more readably. Always bind parameters.
10 How should you implement equals and hashCode on entities?
mediumAvoid using the generated ID alone, because it is null before persist, which changes the hash code while the entity sits in a HashSet. Options are a natural business key, such as an ISBN, or an equals that compares the ID when it is non-null and a constant hashCode, as recommended by Hibernate for generated IDs. Be careful with proxies: compare using instanceof or the Hibernate class helper, not getClass.
java@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Book other)) return false; return id != null && id.equals(other.getId()); } @Override public int hashCode() { return getClass().hashCode(); }11 How does optimistic locking with @Version work?
mediumAdd a version field. Hibernate includes it in the UPDATE condition, WHERE id = ? AND version = ?, and increments it. If another transaction changed the row, zero rows match and an OptimisticLockException is thrown, so the application can retry or tell the user. It avoids database locks and suits low-contention data. Pessimistic locking with LockModeType.PESSIMISTIC_WRITE issues SELECT FOR UPDATE and suits short, high-contention updates.
java@Entity class Account { @Id @GeneratedValue private Long id; @Version private long version; private BigDecimal balance; }12 Which ID generation strategy should you use and why does it matter for batching?
mediumSEQUENCE lets Hibernate fetch IDs in blocks, with an allocationSize, before the insert, so it can batch many INSERTs into few round trips with hibernate.jdbc.batch_size. IDENTITY relies on the database auto-increment and requires the insert to run immediately to learn the ID, so batching is disabled. UUIDs avoid central coordination but are larger, and random ones fragment indexes, so time-ordered UUIDs are preferable.
13 How do you do efficient bulk inserts and updates?
hardSet hibernate.jdbc.batch_size, use a sequence generator, enable order_inserts and order_updates, and flush and clear the persistence context every batch so memory does not grow. For very large changes use a JPQL or native bulk UPDATE, which bypasses the persistence context, so clear it afterwards. For millions of rows consider Spring Batch, or JDBC batch directly.
javafor (int i = 0; i < rows.size(); i++) { em.persist(rows.get(i)); if (i % 50 == 49) { em.flush(); em.clear(); } }14 Explain the first-level and second-level cache.
hardThe first-level cache is the persistence context itself, per session and always on, so loading the same ID twice in one session gives one query and one instance. The second-level cache is shared across sessions, per SessionFactory, optional and provider-backed by something like Ehcache or Infinispan, configured per entity with @Cache. A query cache stores result IDs. Caches add staleness and invalidation concerns, so measure before enabling, and use them for read-mostly reference data.
15 What are DTO projections and why use them?
hardA projection selects only the columns a use case needs and returns them as an interface, a record or a constructor expression, instead of loading full entities. It avoids loading associations, skips dirty-checking overhead and prevents accidentally exposing entity fields through the API. Use them for read-only lists and reports, and entities for writes.
javapublic record OrderRow(Long id, String customerName, BigDecimal total) {} @Query("select new com.shop.OrderRow(o.id, c.name, o.total) from Order o join o.customer c") List<OrderRow> findRows();16 What is open-in-view and should you leave it on?
hardIn Spring Boot, spring.jpa.open-in-view defaults to true, keeping the EntityManager open until the end of the web request, so lazy loading works in controllers and during JSON serialisation. It hides N+1 problems and holds a database connection for the whole request, including slow rendering. Most production guides recommend setting it to false and fetching explicitly in the service layer.
17 How do inheritance mappings differ?
hardSINGLE_TABLE puts the hierarchy in one table with a discriminator column: fast, with no joins, but subclass columns must be nullable. JOINED uses a table per class joined by primary key: normalised, but queries need joins. TABLE_PER_CLASS has a table per concrete class, with polymorphic queries using UNION, and is rarely recommended. MappedSuperclass shares fields without being a queryable entity. Prefer composition over deep hierarchies.
18 How do you find and diagnose performance problems in a JPA application?
hardLog SQL with statistics enabled, hibernate.generate_statistics, or use a datasource proxy to count statements per request and fail tests when the count rises. Look for N+1 patterns, missing indexes with EXPLAIN, large eager graphs, and unbounded result sets. Use pagination at the database with Pageable, and note that fetch joins combined with pagination on collections make Hibernate paginate in memory with a warning.
Frequently asked questions
What changed in Hibernate 6 that interviewers ask about?
The move to the jakarta namespace, a rewritten query engine and SQL model, and changed defaults such as ID generation naming. Spring Boot 3 requires it.
Is Hibernate still relevant versus plain SQL tools?
Yes, it is the default in Spring-based Java stacks. Many teams combine it with jOOQ or native queries for reporting.
What is the single most asked Hibernate question?
The N+1 select problem, followed by lazy versus eager loading and entity states.
Do I need to know the Hibernate Session API or only JPA?
Know JPA in depth and be aware of Session-specific features, since most code uses the JPA API through Spring Data.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- HTML and CSS Interview Questions and Answers
- iOS and Swift Interview Questions and Answers
- Jenkins and CI/CD Interview Questions and Answers
- Kubernetes Interview Questions and Answers
- Machine Learning Interview Questions and Answers
- Manual Testing Interview Questions and Answers
- MERN Stack Interview Questions and Answers
- Next.js Interview Questions and Answers (Next.js 15)
- NLP Interview Questions and Answers
- Node.js Interview Questions and Answers (Node 22)
- NumPy Interview Questions and Answers
- Pandas Interview Questions and Answers