Blog
Top 50 Hibernate Interview Questions
- February 5, 2026
- Posted by: InterviewExpert.org
- Category: Backend Interview Preparation Hibernate
Hibernate Basics & Core Concepts
1. What is Hibernate and why is it used?
Hibernate is a Java-based ORM (Object-Relational Mapping) framework that simplifies database interaction by mapping Java objects to relational database tables and vice versa. Hibernate allows us to focus on business logic instead of boilerplate JDBC code, while still giving control over performance when needed.
Why Hibernate is used
In traditional JDBC:
- Developers write SQL queries
- Manually map ResultSets to objects
- Handle connections, transactions, and exceptions
Hibernate automates all of this.
Internally how Hibernate works?
- Converts HQL / Criteria / JPQL into SQL
- Uses JDBC internally
- Manages:
- Connection lifecycle
- Object mapping
- Caching
- Transaction synchronization
2. What is ORM (Object-Relational Mapping)?
ORM is a technique that maps:
- Java classes → database tables
- Java fields → table columns
- Java objects → table rows
ORM bridges this mismatch.
Example
@Entity
class Employee {
@Id
private Long id;
private String name;
}Mapped to:
EMPLOYEE_TABLE (ID, NAME)3. What are the advantages of Hibernate over JDBC?
Hibernate increases developer productivity while maintaining performance through caching and optimized SQL generation.
| Hibernate | JDBC |
|---|---|
| No boilerplate code | Too much boilerplate |
| Database independent | DB-specific SQL |
| Automatic ORM | Manual mapping |
| Built-in caching | No caching |
| HQL & Criteria | Only SQL |
| Lazy loading | Not available |
4. What are the main components of Hibernate?
Core Components of Hibernate
- Configuration
- SessionFactory
- Session
- Transaction
- Query / Criteria
- Persistent Objects
Flow
Configuration → SessionFactory → Session → Transaction → DB5. What is the role of JPA in Hibernate?
JPA (Java Persistence API) is a specification, not an implementation.
Hibernate is:
- A JPA implementation
- And also provides Hibernate-specific features
JPA vs Hibernate
| JPA | Hibernate |
|---|---|
| Standard API | Implementation |
| Portable | Vendor-specific |
| Limited features | Advanced features |
Example
@Entity
@Table(name="EMP")These annotations come from JPA, not Hibernate.
6. Explain the Hibernate architecture.
Hibernate architecture is layered and provides an abstraction between Java applications and relational databases, handling ORM, caching, transactions, and query execution. Hibernate architecture consists of Configuration, SessionFactory, Session, Transaction, and caching layers that abstract database interactions and manage ORM efficiently.
Main Hibernate Architecture Layers
1. Application Layer
- Contains business logic
- Uses Hibernate APIs to interact with the database
2. Hibernate Framework Layer
Core ORM functionality:
- SessionFactory – Creates sessions (thread-safe)
- Session – Manages entity lifecycle (not thread-safe)
- Transaction – Handles ACID properties
- Query / Criteria / HQL – Query execution
- Persistence Context – First-level cache, dirty checking
3. Caching Layer
- First-Level Cache (mandatory, per session)
- Second-Level Cache (optional, shared across sessions)
4. JDBC Layer
- Manages database connections
- Executes SQL generated by Hibernate
5. Database Layer
- Actual relational database (MySQL, Oracle, PostgreSQL, etc.)
Request Flow
App → Session → Hibernate Engine → JDBC → DBKey internal services
- Connection Pool
- Transaction Manager
- Cache Manager
- Query Translator
7. What is Configuration in Hibernate?
Configuration in Hibernate is a component used to load and read Hibernate settings and mapping information, and to bootstrap the Hibernate framework.
It initializes Hibernate by reading database connection details and entity mappings.
Key Responsibilities of Configuration
- Loads configuration from:
hibernate.cfg.xmlorapplication.properties
- Reads database connection details
- Loads entity mapping metadata
- Creates the SessionFactory
Example
Configuration cfg = new Configuration()
.configure() // loads hibernate.cfg.xml
.addAnnotatedClass(User.class);
SessionFactory factory = cfg.buildSessionFactory();What it loads
- DB URL
- Dialect
- Driver class
- Entity mappings
8. What is SessionFactory?
SessionFactory is a thread-safe, heavyweight Hibernate object that is responsible for creating and managing Session instances. It is created once per application during startup and holds all ORM metadata, such as entity mappings, database configuration, SQL generation strategies, and caching settings.
Internally, SessionFactory also manages the second-level cache, connection pooling, and integration with transaction management. Because its configuration data is immutable after creation, it is safe to be shared across multiple threads. In real-world applications, creating multiple SessionFactory instances is considered a bad practice due to high memory and startup cost, so typically one SessionFactory is used per database.
Example
SessionFactory factory = cfg.buildSessionFactory();9. What is a Session?
A Session in Hibernate represents a single unit of work between the application and the database. It acts as a wrapper over a JDBC connection and is the primary interface through which the application performs CRUD operations. A Session also maintains the first-level cache, also known as the persistence context, which helps Hibernate track entity state changes.
It is not thread-safe and is designed to be short-lived, typically one session per request or per transaction. Hibernate uses the Session to manage entity lifecycle states and perform dirty checking, automatically synchronizing object changes with the database during flush or transaction commit. In short, Session is the main interface between the application and Hibernate ORM.
10. What are the different object states in Hibernate?
Hibernate entities move through Transient, Persistent, Detached, and Removed states based on their interaction with the Session. In Hibernate, an entity object can exist in different states based on its association with the Hibernate Session and the database. These states define how Hibernate manages the object and synchronizes it with the database.
There are four main object states:
1. Transient State
An object is in the Transient state when it is created using the new keyword and is not associated with any Hibernate Session.
2. Persistent State
An object enters the Persistent state when it is saved, persisted, or loaded using a Hibernate Session.
3. Detached State
An object becomes Detached when the Hibernate Session is closed or the object is evicted from the Session.
4. Removed State
An object enters the Removed state when it is marked for deletion using a Hibernate Session.
Session & Persistence
11. Difference between openSession() and getCurrentSession().
openSession() gives a new independent session, while getCurrentSession() is context and transaction scoped.
openSession() | getCurrentSession() |
|---|---|
| Creates a new Session every time | Returns a Session bound to the current context |
| Session must be closed manually | Session is closed automatically |
| Not bound to transaction | Bound to transaction |
| More control, but risk of leaks | Safer for enterprise apps |
12. Difference between get() and load().
get() is safer when unsure about data existence, while load() is optimized for guaranteed data.
Difference between get() and load()
get() | load() |
|---|---|
| Immediately hits database | Uses proxy, DB hit may be delayed |
Returns null if not found | Throws exception if not found |
| Suitable when data may not exist | Suitable when data must exist |
| Eager fetch | Lazy fetch |
13. What is the difference between save(), persist(), and saveOrUpdate()?
Difference between save(), persist(), and saveOrUpdate()
| Method | Behavior |
|---|---|
save() | Saves entity and returns generated ID |
persist() | Saves entity but does not return ID |
saveOrUpdate() | Saves new entity or updates existing one |
Key points:
persist()is JPA standardsave()is Hibernate-specificsaveOrUpdate()avoids checking entity state manually
14. What is a detached object?
A detached object is an object that was saved in the database earlier, but is no longer connected to a Hibernate session. In short, It exists in memory, has database data, but Hibernate is not tracking it anymore.
15. What is transient vs persistent vs detached state?
Transient vs Persistent vs Detached State
Transient
- Created using
new - No Session association
- No database record
Persistent
- Associated with active Session
- Managed by Hibernate
- Changes auto-synced
Detached
- Session closed
- Database record exists
- Changes not tracked
16. How does dirty checking work in Hibernate?
Dirty checking is a mechanism where Hibernate automatically detects changes made to persistent objects. Dirty checking eliminates manual update calls and improves developer productivity
How Dirty checking works?
- Hibernate keeps a snapshot of object state
- Compares snapshot with current state
- Generates SQL
UPDATEif changes exist
Key point:
- No explicit
update()call required
17. What is automatic dirty checking?
Automatic dirty checking means Hibernate tracks changes automatically for all persistent entities within a Session.
Key points:
- Happens at flush time
- Applies only to persistent objects
- Improves consistency
- Can impact performance if too many entities are managed
18. What is flushing and when does it happen?
Flushing is the process where Hibernate synchronizes in-memory object changes with the database. Flush ensures database consistency before query execution or transaction completion.
Flushing happens:
- Before transaction commit
- Before executing a query
- When
flush()is called explicitly
Important Point of Flushing
- Flush writes SQL, commit finalizes transaction
- Flush ≠ Commit
Querying Mechanisms
19. What is HQL (Hibernate Query Language)?
HQL (Hibernate Query Language) is an object-oriented query language used to query Hibernate entities and their properties, not database tables. HQL allows us to query domain objects instead of tables, making applications more portable and maintainable.
Key points of HQL:
- Works on entity names, not table names
- Database-independent
- Converted into SQL internally by Hibernate
- Supports joins, pagination, aggregation, and subqueries
Example of HQL:
FROM Employee e WHERE e.salary > 5000020. Difference between HQL, SQL, and JPQL.
| Feature | HQL | SQL | JPQL |
|---|---|---|---|
| Works on | Entities | Tables | Entities |
| Standard | Hibernate-specific | Database-specific | JPA standard |
| Portability | High | Low | Very High |
| Object-oriented | Yes | No | Yes |
Key points to remember:
- SQL → Table-based, DB-dependent
- HQL → Hibernate ORM specific
- JPQL → JPA specification query language
21. What is Criteria API?
The Criteria API is a programmatic and type-safe way to build queries dynamically without writing query strings. Criteria API is preferred when queries are built dynamically at runtime.
Key points of Criteria API:
- Useful for dynamic queries
- Avoids string-based query errors
- Type-safe (especially JPA Criteria)
- Supports pagination and conditions
22. What are named queries and named native queries?
Named Queries are predefined queries written using HQL or JPQL and identified by a unique name. Named Native Queries are predefined SQL-based queries.
It improve maintainability and catch query issues during application startup.
Key points of Named Query:
- Defined using annotations or XML
- Parsed at startup (fail fast)
- Improves performance and readability
- Reusable across the application
Example of Named Query:
@NamedQuery(
name = "Employee.findAll",
query = "FROM Employee"
)23. How do you execute native SQL queries in Hibernate?
Hibernate allows executing native SQL queries when:
- Complex joins are required
- Database-specific features are needed
- Performance is critical
Ways to execute native SQL queries:
createNativeQuery()- Map result to entity or DTO
Example:
session.createNativeQuery(
"SELECT * FROM EMPLOYEE",
Employee.class
);24. How do you implement pagination in Hibernate?
Pagination ensures scalability by loading only the required subset of data. Pagination in Hibernate is implemented by limiting query results using setFirstResult() and setMaxResults() to fetch data in chunks instead of loading everything at once.
Pagination is implemented using:
setFirstResult()→ starting indexsetMaxResults()→ page size
Hibernate Pagination (Core API) Example:
Query<User> query = session.createQuery("FROM User", User.class);
query.setFirstResult(0); // offset
query.setMaxResults(10); // page size
List<User> users = query.list();Mapping & Relationships
25. How do you map one-to-one relationships?
A one-to-one relationship means one entity instance is associated with exactly one instance of another entity.
Real-World Example
User ↔ Profile
- One User has one Profile
- One Profile belongs to one User
Mapping approach:
- Use
@OneToOneannotation - Use
@JoinColumnto define foreign key - Can be unidirectional or bidirectional
Example of one-to-one relationship:
User Entity (Owning Side)
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String username;
@OneToOne
@JoinColumn(name = "profile_id")
private Profile profile;
}Profile Entity (Inverse Side)
@Entity
public class Profile {
@Id
@GeneratedValue
private Long id;
private String address;
@OneToOne(mappedBy = "profile")
private User user;
}Key Points (Interview Important)
@OneToOnedefines the relationship@JoinColumn→ owning side (foreign key)mappedBy→ inverse side- Foreign key stored in User table
26. How do you map one-to-many and many-to-one relationships?
In practice, many-to-one is preferred as it avoids extra join tables.
Many-to-One
- Most common relationship
- Multiple child entities refer to one parent
@ManyToOne
@JoinColumn(name = "dept_id")
private Department department;One-to-Many
- One parent entity mapped to multiple child entities
- Usually mapped using
mappedBy
@OneToMany(mappedBy = "department")
private List<Employee> employees;Key points:
- Many-to-One owns the relationship
- One-to-Many is usually inverse side
- Foreign key is stored in the many-side table
27. How do you map many-to-many relationships?
A many-to-many relationship occurs when multiple records in one table relate to multiple records in another. In real projects, many-to-many is often replaced with an intermediate entity to store extra attributes.
Mapping approach:
- Use
@ManyToMany - Use a join table
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses;Key points:
- Join table contains foreign keys of both entities
- Can be unidirectional or bidirectional
- Often avoided in favor of an extra entity for flexibility
28. What are join tables and when are they used?
A join table is an intermediate table used to manage relationships between two entities when a direct foreign key mapping is not sufficient. It typically contains foreign keys referencing the primary keys of the related tables.
Join tables are used to manage relationships, most commonly many-to-many, by storing foreign keys of the associated entities when a direct foreign key mapping is not sufficient.
It is Used when:
- Mapping many-to-many relationships
- No foreign key can represent the relationship alone
Structure:
JOIN_TABLE
- entity1_id
- entity2_idKey points:
- Contains only foreign keys (and sometimes metadata)
- Helps normalize database design
- Automatically managed by Hibernate
29. What is inheritance mapping in Hibernate?
Inheritance mapping allows mapping Java class inheritance to database tables. JOINED strategy provides better normalization, while SINGLE_TABLE offers better performance
Common strategies:
1. SINGLE_TABLE
- One table for all classes
- Uses discriminator column
- Fast but sparse columns
2. JOINED
- Separate tables per class
- Uses joins
- Normalized and clean
3. TABLE_PER_CLASS
- Separate table per concrete class
- No joins
- Performance overhead for unions
30. Explain @Entity, @Table, @Id, @Column annotations.
@Entity
- Marks a Java class as a Hibernate entity
- Required for ORM mapping
@Table
- Maps entity to a database table
- Allows table name customization
@Table(name = "EMPLOYEE")@Id
- Marks primary key
- Mandatory for every entity
@Column
- Maps class field to table column
- Allows constraints like nullable, unique, length
@Column(nullable = false)
private String name;Caching & Performance
31. What is first-level cache?
The first-level cache is the default cache in Hibernate and is associated with the Session. Every Session has its own first-level cache, which stores objects that are loaded or saved within that Session. First-level cache improves performance by avoiding repeated database calls within the same session.
Key points on first-level cache:
- Enabled by default
- Scoped to a Session
- Cannot be disabled
- Stores persistent objects
- Prevents repeated database hits within the same Session
32. What is second-level cache?
The second-level cache is an optional cache that is associated with the SessionFactory and shared across multiple Sessions. Second-level cache reduces database access across multiple sessions and improves scalability.
Key points on second-level cache:
- Disabled by default
- Shared across Sessions
- Stores entity data, collections, and associations
- Requires external cache provider
- Improves performance for read-heavy applications
33. What is query cache?
Query Cache is a Hibernate feature that stores the result of a database query, so the same query does not hit the database again. It remembers query results to improve performance. Query Cache works together with Second-Level Cache, It stores IDs of results, not actual objects.
Example:
- First time → Query runs on database
- Next time (same query) → Result comes from cache, not DB 😊
Key points on query cache:
- Must be explicitly enabled
- Stores query result IDs
- Depends on second-level cache
- Best for frequently executed read-only queries
34. Which cache providers are available in Hibernate?
Hibernate supports multiple second-level cache providers. Provider must be configured explicitly and its choice depends on scalability and clustering needs.
Ehcache is commonly used for simple setups, while Infinispan and Hazelcast are preferred for distributed caching.
Common cache providers in hibernate:
- Ehcache
- Hazelcast
- Infinispan
- Redis (via integrations)
- Caffeine
35. Explain fetching strategies (lazy vs eager).
Fetching strategy defines when related entities are loaded. Lazy fetching is preferred by default to avoid unnecessary database access.
Lazy Fetching (FetchType.LAZY)
- Data loaded only when accessed
- Better performance
- Default for collections
Eager Fetching (FetchType.EAGER)
- Data loaded immediately
- Can cause performance issues
- Risk of unnecessary joins
36. What is the N+1 select problem and how to fix it?
N+1 is a common performance issue and is usually fixed using fetch joins or batch fetching.
The N+1 select problem occurs when:
- One query loads parent entities
- N additional queries load child entities individually
The Problem (N + 1 Queries)
Scenario
- You have Department and Employee
- One Department has many Employees
What happens normally?
- 1 query is fired to get all departments
- For each department, Hibernate fires one more query to get its employees
So if you have:
- 1 query for departments
- N departments
Total queries = 1 + N, This is bad for performance
Example
If there are 5 departments:
- 1 query → get all departments
- 5 queries → get employees for each department
Total = 6 queries
Solutions of N+1 Queries Problem
1. Use JOIN FETCH
What it does:
- Fetches departments and employees together in one query
Example
SELECT d FROM Department d
JOIN FETCH d.employeesResult
✔ Only 1 query
✔ No extra employee queries
Best when you know you need employees immediately
2. Use Batch Fetching
What it does:
- Instead of firing one query per department,
- Hibernate fetches employees in batches
Example
@BatchSize(size = 10)Result
- 1 query for departments
- Few queries for employees (not N)
Good when JOIN FETCH is not suitable
37. How do you optimize Hibernate performance?
Hibernate performance optimization involves proper configuration and query design. Hibernate performance tuning is about reducing database calls and controlling the persistence context.
Key optimization techniques:
- Use lazy loading
- Avoid N+1 problem
- Enable second-level cache wisely
- Use pagination
- Use batch processing
- Prefer projections for large data
- Limit persistence context size
Transactions & Concurrency
38. How are transactions handled in Hibernate?
Hibernate handles transactions using the Transaction API, ensuring data consistency and atomicity during database operations. Transactions can be managed programmatically or declaratively (commonly with Spring).
Hibernate transactions ensure that all database operations either complete successfully or roll back entirely.
Transaction flow
Session → beginTransaction() → DB operations → commit()/rollback()39. Difference between optimistic and pessimistic locking.
Optimistic locking assumes conflicts are rare, while pessimistic locking assumes conflicts are frequent.
| Optimistic Locking | Pessimistic Locking |
|---|---|
| No lock on database row | Locks database row |
| Uses versioning | Uses DB-level locks |
| Better performance | Lower performance |
| Suitable for low conflict | Suitable for high conflict |
| Detects conflict at commit | Prevents conflict upfront |
40. What is the @Version annotation?
The @Version annotation is used to implement optimistic locking in Hibernate. It maintains a version column that Hibernate checks before updating a record.
@Version helps Hibernate detect concurrent updates and maintain data integrity.
Example
@Version
private int version;41. How do you configure transaction timeout?
Transaction timeout defines the maximum time a transaction is allowed to run before being rolled back automatically. Transaction timeout avoids resource blocking caused by long-running transactions.
Ways to configure:
- Using Hibernate properties
- Using Spring
@Transactional(timeout = …) - Using JTA transaction manager
42. What are isolation levels supported by Hibernate?
Hibernate supports the standard JDBC isolation levels, which control how transactions interact with each other. Hibernate relies on the database to enforce isolation levels for transactional consistency.
Isolation levels:
- READ_UNCOMMITTED – Allows dirty reads
- READ_COMMITTED – Prevents dirty reads
- REPEATABLE_READ – Prevents dirty and non-repeatable reads
- SERIALIZABLE – Strictest level, highest isolation
Integration & Tools
43. How do you integrate Hibernate with Spring?
Hibernate is integrated with Spring by configuring a DataSource, SessionFactory (or EntityManager), and enabling transaction management. Spring then manages Hibernate sessions and transactions automatically.
In Short, Hibernate is integrated with Spring using Spring ORM, where Spring manages the SessionFactory, transactions, and dependency injection.
Step-by-step (Simple Explanation)
1. Add Dependencies
You add Spring ORM and Hibernate dependencies.
(In Spring Boot, these come automatically with JPA starter.)
2. Configure DataSource
Spring creates the database connection.
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=pass3. Configure Hibernate Session / EntityManager
- Spring creates SessionFactory / EntityManagerFactory
- Hibernate becomes the JPA provider
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true4. Enable Transaction Management
Spring manages transactions using @Transactional.
@Transactional
public void saveEmployee(Employee emp) {
session.save(emp);
}✔ No manual commit or rollback
✔ Spring handles it
5. Use Repositories / DAO
You interact with DB using:
- Hibernate Session
- or Spring Data JPA Repositories
public interface EmployeeRepo extends JpaRepository<Employee, Long> {
}44. What is Hibernate Validator?
Hibernate Validator is a framework used to validate object data using annotations, before saving it to the database. It is the reference implementation of the Bean Validation (JSR 380 / Jakarta Validation) specification. Hibernate Validator helps enforce validation rules at the object level, reducing database errors.
Common annotations:
@NotNull@Size@Email@Min,@Max
Example:
@NotNull
@Size(min = 3, max = 50)
private String name;- Name cannot be null
- Name length must be between 3 and 20
If validation fails → data is not saved
45. What is Hibernate Envers?
Hibernate Envers is a Hibernate module used for auditing and versioning entity changes over time. It provides out-of-the-box auditing without writing custom audit logic.
Key points:
- Automatically tracks insert, update, and delete operations
- Stores historical data in audit tables
- Useful for compliance and tracking changes
- Enabled using
@Audited
Example:
@Audited
@Entity
class Employee { }Use cases:
- Audit logs
- Data history tracking
- Regulatory compliance
46. How do you log Hibernate SQL for debugging?
Hibernate SQL logging helps developers debug queries and performance issues. SQL logging is essential during development but should be avoided in production for performance reasons.
Common ways:
- Enable
show_sql - Enable formatted SQL
- Enable parameter logging
Spring Boot configuration:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE47. What design patterns are used in Hibernate?
Hibernate internally uses several well-known design patterns to achieve flexibility and scalability.
Important patterns:
- Factory Pattern –
SessionFactory - DAO Pattern – Data access abstraction
- Proxy Pattern – Lazy loading
- Template Pattern – HibernateTemplate (older versions)
- Singleton Pattern – SessionFactory lifecycle
- Strategy Pattern – Dialects, caching strategies
Advanced & Best Practices
48. What is @DynamicUpdate and when to use it?
@DynamicUpdate is a Hibernate annotation that instructs Hibernate to generate SQL UPDATE statements dynamically, including only the modified columns instead of all columns. @DynamicUpdate helps optimize update queries by modifying only changed columns, reducing unnecessary database overhead.
Key points:
- Default behavior: Hibernate updates all columns
- With
@DynamicUpdate: only changed fields are updated - Reduces unnecessary database writes
- Useful for wide tables with many columns
Example:
@Entity
@DynamicUpdate
class Employee {
private String name;
private double salary;
}49. How do you handle LazyInitializationException?
LazyInitializationException occurs when a lazy-loaded association is accessed outside the active Hibernate Session. LazyInitializationException is best handled by fetching required data within the transaction boundary.
Common causes:
- Session closed before accessing lazy data
- Accessing entity in controller after transaction ends
Solutions:
- Fetch required data within the transaction
- Use JOIN FETCH in queries
- Enable Open Session in View (OSIV) (with caution)
- Use DTO projections
- Change fetch type to EAGER (not recommended generally)
Best practice:
- Prefer JOIN FETCH or DTOs
- Avoid OSIV in large applications
50. What are best practices for Hibernate in large applications?
In large-scale applications, Hibernate must be used carefully to ensure performance, scalability, and maintainability.
Best practices:
- Use LAZY fetching by default
- Avoid N+1 select problem
- Limit persistence context size
- Use DTO projections for read-only use cases
- Enable second-level cache selectively
- Use batch processing for bulk operations
- Use pagination for large result sets
- Monitor SQL logs and performance
- Handle transactions at service layer
Architectural practices:
- Keep entities simple
- Avoid business logic inside entities
- Clearly define transaction boundaries