Hibernate is a powerful Object-Relational Mapping (ORM) framework that simplifies database interaction in Java applications. It provides an abstraction over JDBC by mapping Java objects to relational database tables, eliminating the need for most SQL code. Hibernate is used by companies like Uber, Airbnb, Google, Netflix, and Amazon.
1. What is Hibernate?
Hibernate is an open-source ORM framework for mapping Java objects to relational database tables. It automates CRUD (Create, Read, Update, Delete) operations, reducing the need for manual SQL queries. Hibernate manages object persistence and database communication efficiently.
2. What are the advantages of using Hibernate
- Simplifies database operations using ORM.
- Supports HQL (Hibernate Query Language), similar to SQL but object-oriented.
- Provides caching and lazy loading for improved performance.
- Ensures database independence and portability.
- Handles transactions automatically.
3. What is ORM in Hibernate?
ORM (Object-Relational Mapping) is a technique that maps Java objects to database tables. It automates data persistence and retrieval, minimizing manual SQL handling and enabling developers to work directly with objects instead of tables.
4. Advantages of Hibernate over JDBC
| Feature | Hibernate | JDBC |
|---|---|---|
| ORM Support | Automatic | Manual |
| Coding Effort | Low | High |
| Database Portability | High | Low |
| Query Caching | Supported | Not Supported |
| Transaction Management | Automatic | Manual |
5. Important Interfaces in Hibernate
- SessionFactory: Creates and manages Session instances.
- Session: Primary interface between the application and database, maintains the first-level cache.
- Transaction: Represents a unit of work, handles commit and rollback.
- Query: Used for creating and executing HQL or native SQL queries.
- SessionFactoryBuilder: Builds a SessionFactory based on configuration settings.
6. List some of the databases supported by Hibernate.
MySQL, Oracle, PostgreSQL, H2, DB2, Microsoft SQL Server, Sybase, SQLite.
7. What is Java Persistence API (JPA)?
JPA is a specification for managing relational data using ORM in Java. Hibernate is one of its implementations.
- Spring Data JPA reduces boilerplate for CRUD and query operations.
- Spring Repository provides interfaces for data access with support for pagination and sorting.
8. Explain Inheritance Mapping in Hibernate
Inheritance Mapping defines how class hierarchies are stored in relational tables. Hibernate supports:
- Single Table: All classes stored in one table.
- Table per Class: Each subclass stored in a separate table.
- Joined Table: Parent and child tables linked via foreign keys.
9. What is HQL?
HQL (Hibernate Query Language) is an object-oriented query language that uses entity and property names instead of table and column names. It supports aggregation, joins, and polymorphic queries.
10. How to Create HQL Queries
- First, create an HQL Query String including entity name, property name, and relationships in the query.
- Create a query Object by using org.hibernate.query.Query interface for creating and executing queries.
- Also, query can be created by using createQuery()
- Set Parameters using setParameter() is optional.
- Execute the Query using methods like list() to retrieve the data or listing of results.
- uniqueResult() for retrieving a single result.
Session session = sessionFactory.openSession();
String hql = "FROM Employee WHERE department.name = :deptName";
Query<Employee> query = session.createQuery(hql, Employee.class);
query.setParameter("deptName", "Engineering");
List<Employee> employees = query.list();
session.close();
11. How Can We Add Criteria to a Query?
Hibernate provides the Criteria API to build dynamic queries using an object-oriented approach.
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.eq("category", "Programming"));
criteria.add(Restrictions.between("price", 100.0, 500.0));
List<Product> products = criteria.list();
12. What is a Session in Hibernate?
Session represents the single unit of work that acts as a gateway for interacting with the databases, Hibernate session is the primary interface for working with databases. Session provides various important functions such as
- Transaction Management
- Caching
- Lazy Loading
- Data Retrieval Strategies
- Object Persistence and Retrieval
It also handles Data Relationship Handling where developers can manage and define relationships between objects, specifying fetching strategies, and overflow of behaviors.
13. What is SessionFactory?
SessionFactory creates and manages Session instances. It is thread-safe and shared across threads. It loads configuration, manages connection settings, and handles caching metadata.
public class HibernateUtil {
private static final SessionFactory sessionFactory =
new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
14. Is Session Thread-Safe?
No, a Session is not thread-safe, but SessionFactory is. Each thread should use its own Session instance to avoid data inconsistency.
15. Difference Between save() and persist()
| Property | save() | persist() |
|---|---|---|
| Return Value | Returns generated ID | Returns void |
| ID Generation | Mandatory | Optional |
| Cascade | Not cascaded automatically | Cascaded |
| Flush | Immediate SQL INSERT | No immediate SQL |
| Transient Instance | Allowed | Must be transient |
16. Difference Between get() and load()
| Property | get() | load() |
|---|---|---|
| Return Type | Actual object | Proxy object |
| Database Hit | Always | Deferred |
| Missing Object | Returns null | Throws ObjectNotFoundException |
| Fetch Type | Eager | Lazy |
| Use Case | When existence is uncertain | For lazy loading |
Hibernate Interview Questions For Intermediate
17. Difference between update and merge
| Property | update() | merge() |
|---|---|---|
| Object Type | Persistent | Detached or transient |
| Return Type | void | Managed instance |
| Unsaved Transient | Throws exception | Allowed |
| State Copy | Copies all fields | Copies only changed fields |
| Performance | May trigger more updates | Fewer SQL updates |
18. Difference Between First-Level and Second-Level Cache
| Property | First-Level Cache | Second-Level Cache |
|---|---|---|
| Scope | Per Session | Across Sessions |
| Storage | Memory | Configurable (memory/disk) |
| Concurrency | Single session | Multi-session |
| Customization | Limited | Fully configurable |
| Cached Items | Entities | Entities, collections, queries |
19. Difference Between getCurrentSession() and openSession()
| Property | getCurrentSession() | openSession() |
|---|---|---|
| Lifecycle | Managed by Hibernate | Managed manually |
| Scope | Current transaction | Independent |
| Auto Close | Yes | No |
| Reuse | Within same transaction | Across transactions |
| Use Case | Short-lived tasks | Long-running sessions |
20. Difference Between save() and saveOrUpdate()
| Property | save() | saveOrUpdate() |
|---|---|---|
| Entity Type | Transient | Detached or transient |
| Existing Entity | Throws exception | Updates existing record |
| Entity State | Becomes transient | Becomes persistent |
| Use Case | Always create | Create or update |
21. States of the object in Hibernate
- Transient: Not associated with any Session or database.
- Persistent: Associated with an open Session and database; changes are tracked.
- Detached: Was persistent but Session is closed.
- Removed: Deleted from the database and no longer managed.
22. How to Create an Immutable Class in Hibernate
@Immutable
public final class ImmutableEmployee {
private final String name;
private final int age;
private ImmutableEmployee(String name, int age) {
this.name = name;
this.age = age;
}
public static ImmutableEmployee create(String name, int age) {
return new ImmutableEmployee(name, age);
}
public String getName() { return name; }
public int getAge() { return age; }
}
Immutable classes are thread-safe and represent read-only entities.
23. What is automatic dirty checking in Hibernate?
Automatic dirty checking ensures that any changes made to persistent objects are automatically detected and synchronized with the database during transaction commit.
Employee emp = session.get(Employee.class, 1L);
emp.setAge(31);
session.getTransaction().commit(); // Hibernate updates automatically
No explicit update() is required.
24. Is Hibernate prone to SQL injection attacks?
No, Hibernate is safe from SQL injection when using parameter binding in HQL or Criteria queries. It treats parameters as data values, not executable SQL.
Query query = session.createQuery(
"FROM User WHERE username = :username AND password = :password");
query.setParameter("username", username);
query.setParameter("password", password);
25. What are the most commonly used annotations available to support hibernate mapping?
Hibernate provides several annotations to map Java classes with database tables. These annotations define how Java entities correspond to database structures.
I. @Entity:
Marks a class as a persistent entity representing a table in the database.
@Entity
@Table(name = "employees")
public class Employee {
}
II. @Table:
Specifies table details associated with the entity.
@Table(name = "employees")
III. @Id:
Defines the primary key of the entity.
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
IV. @GeneratedValue:
Specifies the generation strategy for primary keys.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
V. @Column:
Maps a class field to a specific table column.
@Column(name = "employee_name") private String name;
VI. @OneToMany and @ManyToOne:
Defines one-to-many or many-to-one relationships between entities.
@ManyToOne @JoinColumn(name = "department_id") private Department department;
VII. @ManyToMany:
Defines a many-to-many relationship between entities using a join table.
@ManyToMany
@JoinTable(name = "student_courses", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id"))private List<Course> courses;
26. Explain Hibernate architecture.
Hibernate architecture is layered to separate application logic from database operations. Each component plays a specific role in ORM, transaction handling, and database communication.
Main Components of Hibernate Architecture:
I. Application Layer: Topmost layer where application code resides. It interacts with Hibernate APIs for CRUD operations and transactions.
II. Hibernate API
Provides core interfaces such as:
- SessionFactory: Creates Session instances.
- Session: Represents a single interaction with the database.
- Transaction: Manages commit and rollback operations.
III. Configuration: Responsible for setting up database connection properties, dialects, and mapping files.
Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
IV. SessionFactory: A heavyweight, thread-safe object created once per application. Used to open sessions.
SessionFactory sessionFactory = new Configuration()
.configure("hibernate.cfg.xml")
.buildSessionFactory();
V. Session: Represents a single unit of work with the database. Handles object lifecycle and CRUD operations.
Session session = sessionFactory.openSession();
Employee emp = session.get(Employee.class, 1L);
session.close();
VI. Transaction: Manages atomic operations with commit() and rollback().
Transaction tx = session.beginTransaction();
tx.commit();
VII. Mapping Metadata: Defines mapping between Java objects and database tables using annotations or XML.
VIII. ORM Layer: Handles the conversion between Java objects and database records.
27. What is the Criteria API in Hibernate?
The Criteria API provides a type-safe and object-oriented way to build queries dynamically in Java, without using SQL or HQL directly. It allows for runtime query creation with filtering, projections, and sorting.
Example: Fetch employees aged 30 with salary greater than 50,000
Using HQL:
String hql = "FROM Employee WHERE age = :age AND salary > :salary";
Query query = session.createQuery(hql);
query.setParameter("age", 30);
query.setParameter("salary", 50000);
List<Employee> employees = query.list();
Using Criteria API:
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> root = cq.from(Employee.class);
Predicate age = cb.equal(root.get("age"), 30);
Predicate salary = cb.greaterThan(root.get("salary"), 50000);
cq.where(cb.and(age, salary));
List<Employee> employees = session.createQuery(cq).getResultList();
Key Components:
- CriteriaBuilder: Entry point for query construction.
- CriteriaQuery: Defines query structure.
- Root: Represents entity in the query.
- Predicate: Represents filtering conditions.
28. What does session.lock() method in Hibernate do?
session.lock() is used to apply pessimistic locking on an entity. It prevents other transactions from modifying the same data until the current lock is released.
Purpose:
- Maintains data consistency in concurrent transactions.
- Prevents conflicting updates on shared records.
Locking Types in Hibernate:
- Optimistic Locking: Uses versioning to detect conflicts.
- Pessimistic Locking: Physically locks rows in the database until a transaction completes.
session.lock() explicitly requests a pessimistic lock on an object to prevent concurrent modifications.
29. What is Hibernate caching?
Caching improves performance by storing frequently accessed data in memory to minimize database calls.
Types of Hibernate Caching:
I. First-Level(Session) Cache:
- It is enabled by default and cache mapped with Hibernate Session.
- It stores objects of the current session which are recovered.
- It also provides data consistency at transaction level.
II. Second-Level(Session Factory) Cache:
- In the same Sessionfactory, the cache is distributed among all the sessions created.
- It caches data used in different sessions.
- It also provides data consistency at application level.
Hibernate Interview Questions For Experienced
30. When is merge() method of the hibernate session useful?
merge() is used to update a detached entity (an object not currently associated with any session) back into persistence context.
Entity States in Hibernate:
- Transient: Newly created, not persisted.
- Persistent: Managed by a Hibernate session.
- Detached: Was persistent but session is closed.
Example:
Employee detachedEmp = new Employee();
detachedEmp.setId(1L);
detachedEmp.setName("Jane Smith");
Session session = sessionFactory.openSession();
session.beginTransaction();
Employee updated = (Employee) session.merge(detachedEmp);
session.getTransaction().commit();
session.close();
merge() ensures detached entities are synchronized with the database.
31. Does Hibernate support Native SQL Queries?
Yes. Hibernate allows execution of native SQL queries using the createSQLQuery() method for database-specific operations.
Example:
Session session = sessionFactory.openSession();
session.beginTransaction();
String sql = "SELECT name, salary FROM employees";
SQLQuery query = session.createSQLQuery(sql);
List<Object[]> results = query.list();
session.getTransaction().commit();
session.close();
Native queries are useful for optimized queries or database-specific features not supported by HQL.
32. What happens when the no-args constructor is absent in the Entity bean?
Hibernate uses reflection to instantiate entities. Without a no-argument constructor, Hibernate cannot create entity objects during data retrieval, leading to runtime errors.
Incorrect Example:
@Entity
public class Employee {
@Id
private Long id;
public Employee(String name) { this.name = name; }
}
Correct Example:
@Entity
public class Employee {
@Id
private Long id;
public Employee() {}
public Employee(String name) { this.name = name; }
}
Always include a no-args constructor in entity classes.
33. Can we declare the Entity class final?
Yes, but it is not recommended. Declaring an entity as final prevents Hibernate from creating proxies, which affects lazy loading and runtime enhancements.
@Entity
public final class Employee {
@Id
private Long id;
}
Use final only if proxying or lazy loading is not required.
34. Explain Query Cache?
The Query Cache stores query results in memory. When the same query executes again with identical parameters, results are fetched from cache rather than querying the database.
Steps to Enable Query Cache:
- Enable second-level cache in configuration.
- Mark query as cacheable:
Query query = session.createQuery("FROM Employee");
query.setCacheable(true);
This improves performance for repeated queries with static parameters.
35. How to solve the N+1 SELECT problem in Hibernate?
The N+1 SELECT problem happens when Hibernate executes multiple queries for each associated entity instead of one optimized join query.
Solutions:
I. Batch Fetching: Fetches entities in batches to reduce the number of queries.
@Entity
@BatchSize(size = 10)
public class Department { }
II. Fetch Join: Loads related entities in a single query using JOIN FETCH.
String hql = "SELECT d FROM Department d JOIN FETCH d.employees WHERE d.id = :id";
Department dept = session.createQuery(hql, Department.class)
.setParameter("id", 1L)
.uniqueResult();
Both techniques minimize database round-trips.
36. What is a Single Table Strategy?
A Single Table Strategy is an inheritance mapping approach where an entire class hierarchy is mapped to a single table. A discriminator column differentiates subclass types.
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "vehicle_type")
public abstract class Vehicle { }
@Entity
@DiscriminatorValue("car")
public class Car extends Vehicle {
private int numberOfDoors;
}
@Entity
@DiscriminatorValue("motorcycle")
public class Motorcycle extends Vehicle {
private boolean hasSideCar;
}
37. What are the benefits of NamedQuery?
Named Queries are pre-defined static queries defined in annotations or XML.
Advantages:
- Reusability: Query defined once, reused across multiple classes.
- Performance: Compiled and cached at startup.
- Maintainability: Centralized query definitions.
- Clarity: Separation between application logic and query logic.
38. What is the purpose of the @DynamicUpdate annotation in Hibernate?
@DynamicUpdate optimizes entity update operations by generating SQL statements that include only the modified columns instead of updating all fields.
Example:
@Entity
@DynamicUpdate
public class Employee {
@Id
private Long id;
private String name;
private String department;
}
Benefits:
- Reduces database traffic
- Improves performance
- Minimizes network overhead