Java Interview Preparation
Hibernate Interview Questions
ORM mapping, fetching, caching, transactions, locking, and query performance.
Hibernate Interview Focus
ORM mapping, fetching, caching, transactions, locking, and query performance.
Interview questions
1. What is Hibernate, and why is it used? Beginner
Hibernate is a Java Object-Relational Mapping framework. It maps Java entities to relational tables and manages persistence, relationships, transactions, dirty checking, lazy loading, and queries. It reduces repetitive JDBC mapping code, but developers still need to understand SQL, indexes, transactions, and execution plans.
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
}2. What is ORM? Beginner
ORM means Object-Relational Mapping. It maps a Java class to a database table, an object to a row, a field to a column, and an object relationship to a foreign-key relationship. ORM reduces conversion code between Java objects and SQL rows, but it does not remove the need to understand database design and SQL.
3. What is the difference between Hibernate and JDBC? Beginner
JDBC is a low-level API where the developer writes SQL, binds parameters, reads ResultSet values, maps rows to objects, and closes resources. Hibernate is a higher-level ORM that maps entities, manages a persistence context, performs dirty checking, and generates much of the SQL. JDBC gives maximum SQL control; Hibernate usually improves productivity for a rich domain model.
4. What is the difference between Hibernate and JPA? Beginner
JPA, now Jakarta Persistence, is a standard specification for persistence APIs and annotations. Hibernate is a popular implementation of that specification and also provides native APIs and features. EntityManager and JPQL are standard; Session, HQL, and several Hibernate annotations are provider-specific. Prefer standard APIs unless a Hibernate feature provides a clear, tested benefit.
5. What is the difference between SessionFactory and Session? Beginner
SessionFactory is a heavyweight, thread-safe factory normally created once for a database or persistence unit. Session is a lightweight, short-lived unit of work and persistence context. SessionFactory holds mappings and can provide second-level cache access; Session holds managed entities and the first-level cache. A Session should normally be used by one request or transaction.
6. Is Hibernate Session thread-safe? Intermediate
No. Session is not thread-safe because it contains mutable persistence-context state, managed entities, pending changes, and transaction information. Do not share one Session between concurrent requests or threads. Use a thread-safe SessionFactory and obtain a separate Session or EntityManager for each unit of work.
7. What are the different entity states in Hibernate? Beginner
The main entity states are transient, persistent or managed, detached, and removed. A new object is transient until persist attaches it. A managed object is tracked by the persistence context. A detached object was managed but is no longer attached. A removed entity is managed and scheduled for deletion. SQL may be delayed until flush or commit.
8. What is the difference between transient, persistent, detached, and removed entities? Intermediate
Transient means Hibernate does not know the new object. Persistent means the object is attached and dirty checking applies. Detached means the object may represent an existing row but changes are not tracked by the current context. Removed means a managed entity has been scheduled for deletion. merge can copy detached state into a managed instance.
9. What is the difference between persist() and save()? Intermediate
persist is the standard Jakarta Persistence operation and makes a new entity managed. save is an older Hibernate-specific operation that historically returned an identifier. Modern code should generally use persist because it is portable and fits the standard entity lifecycle. Use native Hibernate methods only when their specific behaviour is required.
10. What is the difference between persist() and merge()? Intermediate
persist is mainly used for a new entity and makes the same instance managed. merge copies the state of a new or detached object into a managed instance and returns that managed instance. The object passed to merge remains detached, so application code should continue using the returned value. merge can require a lookup and may result in insert or update work.
11. What is the difference between update() and merge()? Intermediate
update is an older Hibernate-specific operation that re-associates the same detached instance with a Session and can fail if that Session already manages the same identity. merge copies state into a managed instance and returns it, making it safer for disconnected workflows. In modern applications, prefer standard merge when detached state must be applied.
12. What is the difference between get() and load()? Beginner
In older Hibernate APIs, get usually loaded an entity immediately and returned null when it was absent. load commonly returned a proxy and could delay the query until a property was accessed. Modern APIs are better described as find for an immediate lookup and getReference for a lazy reference. A missing reference may fail when initialized.
13. What is dirty checking in Hibernate? Intermediate
Dirty checking is Hibernate’s automatic detection of changes to managed entities. Hibernate compares the current managed state with its original snapshot during flush and generates update SQL for changed values. It does not track detached objects. Keep transactions and persistence contexts appropriately small because managing large graphs increases memory and comparison work.
14. What is the persistence context? Intermediate
A persistence context is the set of entity instances currently managed by an EntityManager or Session. It provides identity management, first-level caching, dirty checking, relationship tracking, and write-behind behaviour. Within one context, repeated loads of the same entity identity normally return the same managed object instance.
15. What is the first-level cache in Hibernate? Beginner
The first-level cache is the mandatory persistence-context cache associated with one Session or EntityManager. It is checked before the database and prevents duplicate managed instances for the same identity in that context. It ends when the context closes or is cleared. It is not shared between different sessions.
16. What is the second-level cache? Intermediate
The second-level cache is an optional cache shared by sessions from the same SessionFactory. It can reduce database reads for stable reference data such as countries or categories. It requires a cache provider and a deliberate invalidation and concurrency strategy. It is usually a poor choice for highly volatile or unbounded data.
17. What is the difference between first-level and second-level cache? Intermediate
First-level cache is mandatory, session-scoped, and stores managed entities for one persistence context. Second-level cache is optional, SessionFactory-scoped, and can share cached state between sessions. First-level cache also supports dirty checking; second-level cache mainly reduces repeated database reads. The lookup order is first-level cache, second-level cache, then database.
18. What is the Hibernate query cache? Advanced
The query cache stores result information for selected queries, often entity identifiers rather than complete entity state. It depends on second-level cache entries for entity data and works best for frequently repeated, stable queries. Many parameter combinations, large results, or frequent updates can make invalidation cost greater than the benefit, so enable it selectively and measure hit rates.
19. What is the difference between lazy loading and eager loading? Beginner
Lazy loading delays an association query until the relationship is accessed. Eager loading fetches the association immediately or as part of the provider’s loading plan. Lazy loading usually avoids unused data, but it requires a deliberate fetch plan inside the transaction. Eager loading can prevent detached access but may create large joins, unnecessary data, or N+1 queries.
20. What is LazyInitializationException, and why does it occur? Intermediate
LazyInitializationException occurs when a lazy association or proxy is accessed after its Session or persistence context has closed. Common causes are returning entities directly to a controller, serializing lazy relationships outside a transaction, or accessing a collection after a repository method ends. Load the required data within the service transaction instead of enabling eager loading everywhere.
21. How can you resolve LazyInitializationException? Advanced
Fetch the required relationship inside a transaction using a fetch join, EntityGraph, DTO projection, or explicit initialization while the Session is open. Map entities to DTOs in the service layer and return DTOs from APIs. Avoid the Open Session in View workaround as a general fix because it hides query boundaries and can cause unexpected database access during serialization.
22. What is a Hibernate proxy? Intermediate
A proxy is a runtime-generated object representing an entity without necessarily loading all database state. Accessing the identifier may not initialize it, while accessing another property can trigger SQL. Proxies support lazy loading but can fail after session closure and may affect equality, serialization, or code that assumes an exact runtime class.
23. What is the N+1 query problem? Advanced
N+1 occurs when Hibernate executes one query for parent records and then one additional query for each parent’s association. Loading 100 departments and then accessing employees can produce 101 queries. This increases latency, database load, and connection usage. Detect it in SQL logs, traces, query counts, and Hibernate statistics.
24. How can you identify and solve the N+1 query problem? Advanced
Enable SQL logging in a safe environment, inspect traces and query counts, and look for repeated statements with different identifiers. Solve it with a targeted fetch join, EntityGraph, DTO projection, or batch fetching. Check the result size and pagination behaviour after the change; fetching every relationship at once can create a Cartesian product and make performance worse.
25. What is a fetch join? Intermediate
A fetch join tells Hibernate to load an association as part of the current JPQL or HQL query. For example, select distinct d from Department d left join fetch d.employees loads departments and their employees together. It can prevent N+1 queries, but fetching multiple collections may create duplicate rows, large results, or pagination problems.
26. What is the difference between a fetch join and an entity graph? Advanced
A fetch join puts the fetching decision directly in JPQL or HQL and is useful when the query and relationship selection are closely connected. An EntityGraph defines a reusable fetch plan through annotations or runtime configuration. Fetch joins offer query and filtering control; EntityGraphs help reuse different fetch plans with a common repository query.
27. What is the purpose of mappedBy in entity relationships? Intermediate
mappedBy identifies the inverse side of a bidirectional relationship and points to the field on the owning entity. For example, @OneToMany(mappedBy = "department") refers to the department field in Employee. It tells Hibernate not to create a second relationship mapping or unnecessary join table. mappedBy refers to a Java property, not a database column.
28. What is the owning side of a bidirectional relationship? Intermediate
The owning side controls the foreign-key update in the database. In a Department and Employee relationship, Employee is usually the owner because it contains department_id and @JoinColumn. Updating only Department.employees may not update the foreign key. Use helper methods that update both sides so the in-memory model and database mapping stay consistent.
29. What is cascading in Hibernate? Beginner
Cascading propagates selected lifecycle operations from one entity to related entities. CascadeType.PERSIST can persist children, MERGE can merge them, and REMOVE can delete them; ALL includes every cascade operation. Apply cascades according to ownership and lifecycle. An Order can reasonably cascade to its private OrderItems, but deleting an Employee should not normally delete a shared Department.
30. What is the difference between CascadeType.REMOVE and orphanRemoval? Advanced
CascadeType.REMOVE is triggered when the parent entity itself is removed and propagates deletion to its children. orphanRemoval deletes a child when it is removed from the parent’s relationship collection. Use orphanRemoval only when the child is privately owned and cannot exist meaningfully without that parent. They solve different lifecycle events.
31. What is the difference between FetchType.LAZY and FetchType.EAGER? Beginner
LAZY loads an association when accessed, often through a proxy or lazy collection. EAGER requests that the association be available immediately. Collections are commonly lazy by default, while some singular relationships have eager defaults in Jakarta Persistence, but explicit choices are clearer. Do not change everything to EAGER to hide a LazyInitializationException; define fetch plans per use case.
32. What is HQL, and how is it different from SQL? Beginner
HQL is Hibernate Query Language and uses entity names, entity fields, and object relationships rather than table and column names. SQL queries the database schema directly. Hibernate translates HQL into SQL for the configured database. HQL is useful for portable entity queries, while native SQL is useful for vendor-specific features or carefully optimized database operations.
33. What is the difference between HQL and JPQL? Intermediate
JPQL is the standard query language defined by Jakarta Persistence. HQL is Hibernate’s query language and supports JPQL plus Hibernate-specific extensions. Use JPQL features when provider portability matters. Use HQL extensions only when the Hibernate-specific capability provides a clear benefit and provider coupling is acceptable.
34. What is the difference between JPQL and a native SQL query? Intermediate
JPQL uses entity classes and properties and is generally portable between JPA providers and databases. Native SQL uses tables, columns, and database-specific syntax, so it provides more control but may require explicit result mapping and reduce portability. Use JPQL for common entity operations and native SQL for window functions, CTEs, vendor features, reports, or measured optimizations.
35. What is the difference between flush() and commit()? Intermediate
flush synchronizes pending persistence-context changes by sending SQL to the database, but the transaction remains active and can still roll back. commit completes the database transaction and makes it durable according to the database rules. Hibernate may flush automatically before commit or before certain queries. Flushing is not the same as successful commit.
36. What is optimistic locking, and how does @Version work? Advanced
Optimistic locking assumes conflicts are uncommon and detects them with a version field. When an entity is updated, Hibernate includes the previous version in the WHERE clause and increments it. If another transaction updated the row first, no row matches and Hibernate reports an optimistic-lock exception instead of silently overwriting the other update. The provider manages the @Version value.
@Version
private Long version;37. What is the difference between optimistic and pessimistic locking? Advanced
Optimistic locking does not hold a database lock during the whole business operation; it checks a version during update and may require a retry or conflict response. Pessimistic locking asks the database to lock rows while a short transaction works with them. Optimistic locking gives better concurrency for low-conflict web workflows, while pessimistic locking suits highly contended operations such as limited inventory or balance changes.
38. How do you configure and perform batch inserts and updates in Hibernate? Advanced
Enable JDBC batching with settings such as hibernate.jdbc.batch_size, order inserts and updates where appropriate, and periodically flush and clear the persistence context. flush sends pending SQL and clear prevents thousands of managed entities from remaining in the first-level cache. For very large changes, a bulk JPQL update may be faster, but it bypasses normal entity callbacks and can require clearing the context afterward.
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true39. How do you troubleshoot slow Hibernate queries and performance problems? Advanced
Measure the endpoint, database time, query count, connection wait, and memory before changing code. Enable controlled SQL and bind-parameter logging, inspect execution plans with EXPLAIN, look for N+1 queries and unexpected eager loads, add or validate indexes, select only required columns with DTOs, and paginate large results. Also review transaction duration, JDBC batching, connection-pool metrics, cache hit rates, and garbage-collection pressure.
40. What common Hibernate issues have you faced in production, and how did you resolve them? Advanced
Strong examples include N+1 queries solved with DTO projections or targeted fetch joins; LazyInitializationException solved by loading data inside a transaction and mapping to DTOs; batch-job memory growth solved with periodic flush and clear; lost updates solved with @Version; connection exhaustion solved by reducing transaction duration and fixing slow SQL; and JSON recursion solved by not exposing bidirectional entities directly. Explain the symptom, evidence, root cause, fix, and measured result.
How to Prepare for Java Technical Interviews
Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.
Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.
Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.
