Hibernate Advanced Interview Questions Notes
What is Hibernate?
- Hibernate: An Object-Relational Mapping (ORM) tool used to map Java objects to database tables.
- ORM: Facilitates communication between object-oriented programming and database systems.
Mapping Methods
- Hibernate provides two primary methods for mapping:
- JPA Annotations: Java Persistence API annotations used for mapping.
- XML Configurations: Hibernate uses XML files for configuration (e.g.,
hibernate.cfg.xml
).
- Hibernate is an implementation of JPA, offering functionalities defined by JPA.
Advantages of using Hibernate over JDBC
- Eliminates Boilerplate Code: Reduces repetitive coding by managing database connections automatically.
- Hibernate Query Language (HQL): Provides a more object-oriented query language.
- Implicit Transaction Management: Automatically manages database transactions without manual intervention.
- Exception Handling: Converts checked exceptions to unchecked exceptions, reducing the need for try-catch blocks.
- Caching Support: Enables better performance through caching mechanisms.
Important Interfaces in Hibernate
- SessionFactory:
- Used to retrieve session objects.
- One instance per database connection.
- Session:
- Represents a single unit of work with the database.
- Used for CRUD operations and manages transactions.
- Transaction:
- Represents an atomic unit of work, allowing operations like commit and rollback.
Code Example of Hibernate Implementation
- Obtain session factory using
getSessionFactoryBuilder()
.
- Open a session:
sessionFactory.openSession()
.
- Begin transaction:
session.beginTransaction()
.
- Perform CRUD operations and commit the transaction.
- Close session and session factory.
Annotations in Hibernate
- @Entity: Specifies that a class is an entity and will be mapped to a table.
- @Table: Defines the name of the database table.
- @Id: Specifies the primary key for the entity.
- @GeneratedValue: Indicates how to generate primary key values.
- @Column: Defines the column name for the entity properties.
- Mapping types: One-to-one, Many-to-one, Many-to-many, and more, each with respective annotations.
Types of Mappings in Hibernate
- One-to-One Mapping: A single instance of one entity is associated with a single instance of another.
- Many-to-One Mapping: Many instances of one entity can associate with a single instance of another.
- Many-to-Many Mapping: Multiple instances of two entities can associate with one another.
Example of Mappings
- One-to-One: Employee to PhoneNumber.
- Many-to-One: Multiple Employees to a single Address.
- Many-to-Many: Students to Degrees (with a third table to handle the many-to-many relationship).
Hibernate Configuration Files
- hibernate.cfg.xml: Contains properties for database connection (driver, dialect, username, password).
- Mapping Files: Maps Java objects to database tables (e.g.,
Employee.hbm.xml
).
Steps to Create a Hibernate Application
- Create a POJO (Plain Old Java Object).
- Create a mapping file.
- Create a configuration file for database connection.
- Create a utility class for data operations.
- Run the application to verify results.
Open Session vs. Get Current Session
- GetCurrentSession(): Returns the session associated with the current context; does not need to be explicitly closed.
- OpenSession(): Creates a new session that must be explicitly closed after use.
Get vs. Load Method
- Get(): Loads the data immediately and returns null if data does not exist.
- Load(): Returns a proxy object; data is loaded only when needed; throws an exception if data does not exist.
Caching in Hibernate
Types of Caching
- First Level Cache: Automatically associated with the session object; cannot be disabled.
- Second Level Cache: Optional, can be enabled; enhances performance.
- Query Level Cache: Works in conjunction with second-level cache for caching queries.
Enabling Second Level Cache (Ehcache example)
- Add Ehcache dependency in the project.
- Update
hibernate.cfg.xml
with properties for Ehcache region factory.
- Define regions and timeout configurations in the
ehcache.xml
file.
- Use caching annotations in entity classes (e.g.,
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
).
Finally, interviewer may inquire for more advanced Hibernate questions in follow-up sessions based on interest.