medium.com 5 min read Original Source

Understanding Hibernate: An In-Depth Overview

Introduction

Hibernate stands as a prominent open-source framework for Java, streamlining database interaction within Java applications. It introduces an Object-Relational Mapping (ORM) solution that enables developers to work seamlessly with Java objects, abstracting the complexities of SQL queries. In this guide, we will delve into the key components and concepts that form the robust architecture of Hibernate

Hibernate Architecture Components:

1. Hibernate Configuration

The configuration of Hibernate is pivotal for establishing the framework and fostering the connection between Java applications and databases. Typically stored in an XML file, such as hibernate.cfg.xml, the configuration encompasses essential parameters:

  • Database Connection: Details such as JDBC URL, username, and password for connecting to the database.

  • Dialect: Specifies the SQL dialect of the database, allowing Hibernate to generate appropriate SQL statements.

  • Mapping Files: Defines the mapping between Java objects (POJOs) and database tables using hbm.xml files.

  • Connection Pooling: Configuration for connection pooling, which helps manage and reuse database connections efficiently.

  • Caching: Configures the first-level and second-level caches to optimize data retrieval.

An example of a simple hibernate.cfg.xml file:

<button data-code="

<! – Database connection settings →
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/mydatabase
root
password
<! – JDBC connection pool settings
5
20
300
50
3000
org.hibernate.dialect.MySQLDialect
true
<! – Drop and re-create the database schema on startup →
update
<! – Mention annotated class →

” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
 <! - Database connection settings →
 <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">password</property>
<! - JDBC connection pool settings
 <property name="hibernate.c3p0.min_size">5</property>
 <property name="hibernate.c3p0.max_size">20</property>
 <property name="hibernate.c3p0.timeout">300</property>
 <property name="hibernate.c3p0.max_statements">50</property>
 <property name="hibernate.c3p0.idle_test_period">3000</property>
 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.show_sql">true</property>
<! - Drop and re-create the database schema on startup →
 <property name="hibernate.hbm2ddl.auto">update</property>
<! - Mention annotated class →
 <mapping class="com.example.model.Employee"/>
 </session-factory>
</hibernate-configuration>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
 <! - Database connection settings →
 <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">password</property>
<! - JDBC connection pool settings
 <property name="hibernate.c3p0.min_size">5</property>
 <property name="hibernate.c3p0.max_size">20</property>
 <property name="hibernate.c3p0.timeout">300</property>
 <property name="hibernate.c3p0.max_statements">50</property>
 <property name="hibernate.c3p0.idle_test_period">3000</property>
 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.show_sql">true</property>
<! - Drop and re-create the database schema on startup →
 <property name="hibernate.hbm2ddl.auto">update</property>
<! - Mention annotated class →
 <mapping class="com.example.model.Employee"/>
 </session-factory>
</hibernate-configuration>

Setting the hibernate.hbm2ddl.auto property to create in the Hibernate configuration can create the database schema based on the annotated entities and mappings defined in the application. It generates SQL DDL (Data Definition Language) statements to create tables, indexes, and constraints.

When hibernate.show_sql is set to true, Hibernate logs the generated SQL statements to the console. This includes SQL statements for operations such as SELECTs, INSERTs, UPDATEs, and DELETEs.

2. Session Factory

The SessionFactory, a heavyweight, thread-safe object, manages Session instances. Created during application startup based on configuration settings, it is resource-intensive and typically exists as a singleton. Each SessionFactory often comes with its connection pool.

Example SessionFactory creation:

Each SessionFactory typically comes with its own connection pool.

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

If your application needs to interact with multiple databases, each with its own configuration, you may consider having a separate SessionFactory for each database. This allows you to manage the connections, configurations, and transactions independently for each database.

Creating a SessionFactory is a resource-intensive operation. It involves parsing configuration files, setting up connection pools, and other initialization steps. Frequent creation of new SessionFactory instances can lead to unnecessary resource consumption, such as increased memory usage and CPU cycles.

3. Session:

A Session represents a unit of work in Hibernate, serving as a runtime interface between a Java application and the database. It facilitates operations like storing, updating, and retrieving objects. Both session.get() and session.load() methods are used for object retrieval.

Example Session usage:

// Open a new session
Session session = sessionFactory.openSession();
// Perform database operations
Transaction transaction = session.beginTransaction();
// … perform operations …
transaction.commit();
// Close the session
session.close();
// Open a new session
Session session = sessionFactory.openSession();
// Perform database operations
Transaction transaction = session.beginTransaction();
// … perform operations …
transaction.commit();
// Close the session
session.close();

In Hibernate, both session.get() and session.load() methods are used to retrieve an object from the database.

The session.get() method performs an immediate database query. It fetches the object from the database as soon as the method is called. If the provided identifier is null or the specified entity type is incorrect, the get()method throws an IllegalArgumentException. If an object is returned by get(), it is the actual object from the database, not a proxy. Lazy loading is applied to associations if configured.

The session.load() method does not immediately execute a database query. Instead, it returns a proxy object with the given identifier. The actual database query is executed when a method on the proxy is invoked. load() can throw a ObjectNotFoundException when an operation is performed on the proxy and the actual object is not found in the database.

The session.clear() method in Hibernate is used to detach all currently managed entities from the current Hibernate session. When you invoke session.clear(), it effectively clears the first-level cache (session cache) of Hibernate.

4. Transaction

Transactions ensure the ACID properties of database operations. The Transaction interface in Hibernate provides methods for beginning, committing, and rolling back transactions. The session.flush() method synchronizes the in-memory state with the database.

Example Transaction usage:

// Begin a new transaction
Transaction transaction = session.beginTransaction();
// Perform database operations
// Commit the transaction
transaction.commit();
// Rollback the transaction in case of an error
transaction.rollback();
// Begin a new transaction
Transaction transaction = session.beginTransaction();
// Perform database operations
// Commit the transaction
transaction.commit();
// Rollback the transaction in case of an error
transaction.rollback();

Hibernate itself does not support true nested transactions. However, you can achieve a similar behavior using the savepoints feature provided by the underlying JDBC (Java Database Connectivity) standard. Savepoints allow you to set points within a transaction to which you can later roll back.

The session.flush() method in Hibernate is used to synchronize the in-memory state of the Session with the database. It forces any changes that have been queued up in the Hibernate session to be immediately executed in the database.

The isolation property in a transaction determines how the changes made by one transaction are visible to other concurrently executing transactions.

The isolation property in a transaction determines how the changes made by one transaction are visible to other concurrently executing transactions. In Hibernate, the isolation level is a crucial aspect of transaction management, and it plays a significant role in maintaining the consistency of the database. Different isolation levels offer different trade-offs between consistency and performance. The standard isolation levels, as defined by the SQL standard, are:

1. READ UNCOMMITTED:

The lowest isolation level. Allows a transaction to read uncommitted changes made by other transactions. It may result in dirty reads, non-repeatable reads, and phantom reads.

2. READ COMMITTED:

A transaction can only read committed changes made by other transactions. It prevents dirty reads but may still allow non-repeatable reads and phantom reads.

3. REPEATABLE READ:

Guarantees that if a transaction reads a value, it will see the same value throughout the transaction’s lifetime. Prevents dirty reads and non-repeatable reads but may allow phantom reads.

4. SERIALIZABLE:

The highest isolation level. Ensures complete isolation between transactions. No dirty reads, non-repeatable reads, or phantom reads are allowed.

Transaction tx = session.beginTransaction();
tx.setIsolation(Transaction.SERIALIZABLE); // Set isolation level to SERIALIZABLE
// Perform database operations
tx.commit();
Transaction tx = session.beginTransaction();
tx.setIsolation(Transaction.SERIALIZABLE); // Set isolation level to SERIALIZABLE
// Perform database operations
tx.commit();

The hibernate.transaction.flush_before_completion property in Hibernate is a configuration setting that determines whether the session should be flushed before transaction completion. When this property is set to true, it means that Hibernate will flush (synchronize the in-memory state with the database) before completing the transaction. Conversely, when set to false, the session will not be flushed before transaction completion.

5. Criteria Queries

Criteria queries offer a programmatic and type-safe way to express queries. They are utilized for complex queries involving multiple conditions. Hibernate’s Criteria API provides a type-safe approach to constructing queries.

Example Criteria Query:

<button data-code="// Create a criteria query
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery criteriaQuery = builder.createQuery(Employee.class);
Root root = criteriaQuery.from(Employee.class);
// Add conditions to the query
criteriaQuery.select(root).where(builder.equal(root.get("department"), "IT"));
// Execute the query
List employees = session.createQuery(criteriaQuery).getResultList();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// Create a criteria query
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = builder.createQuery(Employee.class);
Root<Employee> root = criteriaQuery.from(Employee.class);
// Add conditions to the query
criteriaQuery.select(root).where(builder.equal(root.get("department"), "IT"));
// Execute the query
List<Employee> employees = session.createQuery(criteriaQuery).getResultList();
// Create a criteria query
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = builder.createQuery(Employee.class);
Root<Employee> root = criteriaQuery.from(Employee.class);
// Add conditions to the query
criteriaQuery.select(root).where(builder.equal(root.get("department"), "IT"));
// Execute the query
List<Employee> employees = session.createQuery(criteriaQuery).getResultList();

In Hibernate, both CriteriaQuery and Query are used for building and executing queries.

CriteriaQuery is part of the JPA (Java Persistence API) Criteria API, providing a type-safe and programmatic way to define queries. It allows developers to create queries using a fluent interface and is primarily used for constructing queries based on the structure of Java entities. Errors in query construction are detected at compile-time rather than at runtime.

Criteria API Example:

<button data-code="CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Entity.class);
Root root = criteriaQuery.from(Entity.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("propertyName"), value));
List result = session.createQuery(criteriaQuery).getResultList();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Entity> criteriaQuery = criteriaBuilder.createQuery(Entity.class);
Root<Entity> root = criteriaQuery.from(Entity.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("propertyName"), value));
List<Entity> result = session.createQuery(criteriaQuery).getResultList();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Entity> criteriaQuery = criteriaBuilder.createQuery(Entity.class);
Root<Entity> root = criteriaQuery.from(Entity.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("propertyName"), value));
List<Entity> result = session.createQuery(criteriaQuery).getResultList();

Query DSL Example:

<button data-code="QEntity entity = QEntity.entity;
List result = new JPAQueryFactory(entityManager)
.selectFrom(entity)
.where(entity.propertyName.eq(value))
.fetch();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

QEntity entity = QEntity.entity;
List<Entity> result = new JPAQueryFactory(entityManager)
    .selectFrom(entity)
    .where(entity.propertyName.eq(value))
    .fetch();
QEntity entity = QEntity.entity;
List<Entity> result = new JPAQueryFactory(entityManager)
    .selectFrom(entity)
    .where(entity.propertyName.eq(value))
    .fetch();

6. HQL (Hibernate Query Language):

HQL is a powerful object-oriented query language provided by Hibernate. It allows developers to write queries using Java-like syntax, operating on entities and their properties.

<button data-code="// HQL query to retrieve employees in the IT department
String hqlQuery = "FROM Employee WHERE department = :dept";
List employees = session.createQuery(hqlQuery)
.setParameter("dept", "IT")
.getResultList();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// HQL query to retrieve employees in the IT department
String hqlQuery = "FROM Employee WHERE department = :dept";
List<Employee> employees = session.createQuery(hqlQuery)
 .setParameter("dept", "IT")
 .getResultList();
// HQL query to retrieve employees in the IT department
String hqlQuery = "FROM Employee WHERE department = :dept";
List<Employee> employees = session.createQuery(hqlQuery)
 .setParameter("dept", "IT")
 .getResultList();

Conclusion

Hibernate’s architecture, comprising configuration, session management, transactions, and query languages, empowers Java developers to seamlessly interact with databases. This guide has explored the fundamental components and concepts, providing a comprehensive understanding of Hibernate’s architecture. Incorporating Hibernate into your Java projects can enhance database interactions, fostering efficiency and maintainability.

Stay tuned!!! I will be back with some more cool Spring boot tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some claps 👏. And if you have any questions feel free to comment. Thank you.

Thanks a lot for reading till the end. Follow or contact me via:
Email: [email protected]
LinkedIn: https://www.linkedin.com/in/reuben-shumba-a72aaa157/
BuyMeCoffee: https://www.buymeacoffee.com/reubenshumba
REUBEN SHUMBA