Advanced Hibernate Interview Questions

Jul 28, 2024

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

  1. Eliminates Boilerplate Code: Reduces repetitive coding by managing database connections automatically.
  2. Hibernate Query Language (HQL): Provides a more object-oriented query language.
  3. Implicit Transaction Management: Automatically manages database transactions without manual intervention.
  4. Exception Handling: Converts checked exceptions to unchecked exceptions, reducing the need for try-catch blocks.
  5. Caching Support: Enables better performance through caching mechanisms.

Important Interfaces in Hibernate

  1. SessionFactory:
    • Used to retrieve session objects.
    • One instance per database connection.
  2. Session:
    • Represents a single unit of work with the database.
    • Used for CRUD operations and manages transactions.
  3. Transaction:
    • Represents an atomic unit of work, allowing operations like commit and rollback.

Code Example of Hibernate Implementation

  1. Obtain session factory using getSessionFactoryBuilder().
  2. Open a session: sessionFactory.openSession().
  3. Begin transaction: session.beginTransaction().
  4. Perform CRUD operations and commit the transaction.
  5. 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

  1. One-to-One Mapping: A single instance of one entity is associated with a single instance of another.
  2. Many-to-One Mapping: Many instances of one entity can associate with a single instance of another.
  3. 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

  1. hibernate.cfg.xml: Contains properties for database connection (driver, dialect, username, password).
  2. Mapping Files: Maps Java objects to database tables (e.g., Employee.hbm.xml).

Steps to Create a Hibernate Application

  1. Create a POJO (Plain Old Java Object).
  2. Create a mapping file.
  3. Create a configuration file for database connection.
  4. Create a utility class for data operations.
  5. 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

  1. First Level Cache: Automatically associated with the session object; cannot be disabled.
  2. Second Level Cache: Optional, can be enabled; enhances performance.
  3. Query Level Cache: Works in conjunction with second-level cache for caching queries.

Enabling Second Level Cache (Ehcache example)

  1. Add Ehcache dependency in the project.
  2. Update hibernate.cfg.xml with properties for Ehcache region factory.
  3. Define regions and timeout configurations in the ehcache.xml file.
  4. 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.