Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

Hibernate Architecture

Hibernate is a comprehensive framework, and its architecture is made up of several components working together to provide a robust ORM (Object-Relational Mapping) solution. This tutorial will provide an overview of Hibernate's architecture.

Hibernate Architecture:

The primary components of Hibernate architecture are:

  1. Application: The main application you're developing.

  2. Hibernate API: The set of APIs provided by Hibernate to the application for CRUD operations.

  3. Configuration Object: This is the first Hibernate object you create in any Hibernate application. It's used mainly during initialization, and it represents specified database properties in the hibernate.cfg.xml file.

  4. SessionFactory: This is a factory that delivers the Session objects. It reads the Hibernate configuration and connection properties provided and creates a session object.

  5. Session: It provides an interface between your application and the data stored in the database. It's a short-lived object and wraps the JDBC connection. It's the primary interface for persistence operations.

  6. Transaction: This represents a unit of work with the database and is used to ensure that transactions are ACID compliant. Hibernate transactions are managed by the underlying transaction manager.

  7. Query Object: Hibernate uses its query language (HQL), which is an object-oriented extension of SQL. You can also use native SQL with Hibernate.

  8. Criteria Object: This object provides a library of fetch methods for obtaining persistent objects based on certain criteria.

  9. Database: This is the RDBMS that Hibernate apps connect to for data storage and retrieval.

Flow of Hibernate Application:

  1. Configuration: When the Hibernate application is initialized, it reads the configuration properties from the hibernate.cfg.xml file using the Configuration object.

  2. SessionFactory Creation: The Configuration object is then used to create the SessionFactory. It's a thread-safe (global) object, created once during application initialization.

  3. Session Creation: For every database interaction, a new session is created from the SessionFactory.

  4. Persistence Operations: Using the session, the application interacts with the database, performing CRUD operations.

  5. Transaction Management: For every set of operations that need to be atomic, a transaction is started, and either committed (if everything goes well) or rolled back (in case of errors).

  6. Query Execution: If data needs to be fetched or conditions need to be applied, either HQL or Criteria is used.

  7. Session Closing: Once the database operations are over, the session is closed.

  8. SessionFactory Closing: Ideally, the SessionFactory is closed when the application stops.

Advantages of the Architecture:

  1. Layered Architecture: This provides flexibility to integrate with any application environment.

  2. Database Independence: The architecture is designed such that by changing the dialect and a few settings in hibernate.cfg.xml, the application can switch to a different RDBMS.

  3. Caching: Hibernate provides a powerful caching mechanism to cache frequently used data and improve performance.

  4. Lazy Loading: The architecture supports lazy loading of data, ensuring that objects are loaded only when they are accessed.

  5. ACID Transactions: Transactions in Hibernate are ACID compliant, ensuring data integrity.

  6. ORM: The architecture makes Java applications agnostic to the underlying SQL structure, promoting an object-oriented programming approach.

In summary, Hibernate's architecture consists of several components that interact to provide an efficient and effective ORM solution. When you understand this architecture, it can help you make better design decisions and utilize Hibernate more effectively in your applications.

  1. SessionFactory in Hibernate:

    The SessionFactory is a thread-safe object responsible for creating and managing Session instances. It is a heavyweight object and is typically created once during application startup.

    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    
  2. Hibernate Session and SessionFactory relationship:

    The Session is a short-lived object representing a single unit of work, while the SessionFactory is a long-lived object responsible for creating Session instances.

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    
    // Perform database operations using the session
    
    session.close(); // Close the session when done
    
  3. Working of Hibernate Transaction:

    Hibernate transactions ensure data consistency by grouping a set of database operations into a single atomic unit. Transactions are managed using the Transaction interface.

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    
    // Perform database operations
    
    transaction.commit(); // Commit the transaction
    session.close(); // Close the session
    
  4. Hibernate Cache architecture:

    Hibernate uses two levels of caching:

    • First Level Cache: Session-level cache that stores objects within the current session.
    • Second Level Cache: Application-level cache shared across multiple sessions.
    // Enable second-level cache in hibernate.cfg.xml
    <property name="hibernate.cache.use_second_level_cache">true</property>
    
  5. Database connection handling in Hibernate:

    Hibernate uses a connection pool to manage database connections efficiently. Common connection pool implementations include C3P0, DBCP, and HikariCP.

    // Configure connection pool in hibernate.cfg.xml
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    
  6. Hibernate ORM architecture diagram:

    Hibernate ORM architecture diagram depicts the relationship between key components like SessionFactory, Session, Transaction, and the database.

  7. Lazy loading in Hibernate architecture:

    Lazy loading is a technique where related entities are loaded from the database only when accessed. It helps in optimizing performance by avoiding unnecessary database queries.

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Child> children;
    
  8. Integration of Hibernate with other frameworks:

    Hibernate can be integrated with various frameworks and technologies, including:

    • Spring: Using Spring's LocalSessionFactoryBean for session management.
    • Java EE: Integrated with JTA (Java Transaction API) for distributed transactions.
    • Struts: Combined with Struts for web application development.

    Example of Spring integration:

    @Autowired
    private SessionFactory sessionFactory;
    
    public void performDatabaseOperation() {
        try (Session session = sessionFactory.openSession()) {
            // Perform database operations
        }
    }