Hibernate ORM Mastery: Persistence, Mapping, and Interview Guide
In the realm of Java enterprise applications, bridging the gap between Object-Oriented code and Relational Databases is a significant challenge. Hibernate ORM is the most popular solution to this "Object-Relational Impedance Mismatch."
What is Hibernate? Hibernate is an open-source, Object-Relational Mapping (ORM) solution for Java. It maps Java classes to database tables and Java data types to SQL data types.
1. The Hibernate Architecture
Hibernate has a layered architecture which helps the user to operate without having to know the underlying APIs.
- Configuration: Represents the configuration file (hibernate.cfg.xml). It is used to create the SessionFactory.
- SessionFactory: A thread-safe cache of compiled mappings. It is a heavy-weight object used to create Sessions.
- Session: A short-lived object used to get a physical connection with a database. It is not thread-safe.
- Transaction: Represents a unit of work with the database. It handles commit and rollback operations.
2. Hibernate Object States
Understanding the state of an object in Hibernate is critical for managing data persistence.
| State | Description |
|---|---|
| Transient | The object is newly created and not yet associated with a Hibernate Session. |
| Persistent | The object is associated with a session and has an identifier in the database. |
| Detached | The session has been closed or the object has been evicted. It no longer tracks changes. |
3. Hibernate Caching Mechanism
- First-Level Cache (Level 1): Associated with the Session object. It is enabled by default.
- Second-Level Cache (Level 2): Associated with the SessionFactory. It is global across the application.
4. Top Hibernate Interview Questions
Q1. What is the difference between get() and load() methods?
get(): Returns null if the object is not found. It always hits the database immediately (Eager loading).
load(): Throws an exception if not found. It returns a Proxy object and only hits the DB when needed (Lazy loading).
Q2. What is HQL (Hibernate Query Language)?
HQL is an object-oriented query language. Instead of tables and columns, it operates on Persistent Objects and their properties. It is database-independent.
5. Hibernate Mapping
- One-to-One: Exactly one entity related to another (e.g., Person and Passport).
- One-to-Many: One entity related to multiple entities (e.g., Department and Employees).
- Many-to-Many: Requires a "Join Table" (e.g., Students and Courses).