Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Hibernate Framework Tutorial: Comprehensive Guide for Java Developers

Published On: May 6, 2025

A popular Java Object-Relational Mapping (ORM) framework, Hibernate makes it easier for Java apps and relational databases to communicate with one another. It has become a crucial skill for Java developers. Gain fundamental understanding with this Hibernate framework tutorial for Java developers. Explore our Hibernate course syllabus to get started with building powerful Java persistence applications.

Hibernate Introduction

For the Java platform, Hibernate is a robust open-source Object-Relational Mapping (ORM) framework. Consider it a manager and translator between your relational database and Java objects. It manages the specifics of data persistence by acting as a layer between your application and the database.

  • Object-Relational Mapping (ORM): Java objects can be used to interact with your database to Hibernate.
  • Automatic Persistence: Hibernate makes it automatic to load data from the database back into your Java objects and save the state of your Java objects to the database.
  • Simplified Data Access: Hibernate makes data access considerably easier and more developer-friendly by abstracting away the complexity of JDBC.
  • Database Independence: Hibernate offers a degree of abstraction, even though SQL dialects (such as MySQL, PostgreSQL, etc.) can differ amongst databases.
  • Transaction Management: Hibernate ensures data consistency and integrity by integrating effectively with transaction management systems.
  • Caching: To enhance application performance, Hibernate offers caching technologies at two separate levels (first-level and second-level cache).
  • Associations and Relationships: Hibernate manages the corresponding database relationships (foreign keys, join tables) and the relationships between your Java objects (such as many-to-many, one-to-many, and one-to-one).
  • Hibernate Query Language (HQL): HQL is an object-oriented query language that Hibernate offers. It functions similarly to SQL but instead of working directly with database tables and columns, it works with your Java objects and their properties.

Recommended: Hibernate Online Course Program.

Setting Up Environment for Hibernate Framework

Here are the steps involved in environment setup for hibernate framework:

Java Development Kit (JDK): Since Hibernate is a Java framework, a functional JDK must be installed on your computer.

Download the JDK from the official website and follow instructions. 

Verify with the following code in the command prompt:

java -version

javac -version

Integrated Development Environment (IDE): Although a basic text editor can be used to create Hibernate applications, an IDE greatly simplifies the process with capabilities like project management. Popular IDEs: Eclipse, NetBeans, and IntelliJ IDEA 

Maven or Gradle (Build Tool): These tools assist you in building your application and managing the dependencies of your project, such as the Hibernate libraries itself. The procedure of downloading and adding the required JAR files is automated.

Hibernate Dependencies: The Hibernate library and its dependencies must be incorporated into your project. Maven or Gradle can be useful in this situation.

In your IDE, create a new Maven project, which will produce a simple pom.xml file.

Add the following dependence inside the tags after opening the pom.xml file:

<dependency>

    <groupId>org.hibernate.orm</groupId>

    <artifactId>hibernate-core</artifactId>

    <version>6.5.0.Final</version> </dependency>

  • groupId: Indicates which organization is responsible for publishing the artifact.
  • artifactId: The particular library’s name.
  • version: The Hibernate library version that you wish to utilize. The most recent stable version is available on Maven Central.

Important Dependencies: 

  • Database Driver: You must have the JDBC driver for the particular database you plan to use, such as the H2 Database Engine, PostgreSQL JDBC Driver, or MySQL Connector/J. Additionally, include its dependence in your pom.xml. Example: MySQL.

<dependency>

    <groupId>com.mysql</groupId>

    <artifactId>mysql-connector-j</artifactId>

    <version>8.3.0</version> </dependency>

  • Logging Framework: Hibernate logs internally using a logging framework, such as SLF4j. Usually, an implementation such as Logback or Log4j 2 must be included. For instance, utilizing Logback:

<dependency>

    <groupId>ch.qos.logback</groupId>

    <artifactId>logback-classic</artifactId>

    <version>1.5.3</version>

</dependency>

  • These dependencies will be downloaded automatically by Maven and made available to your project.

Database: Hibernate facilitates interaction with relational databases as it is an Object-Relational Mapping (ORM) framework. A database server must be operational.

  • Popular options include Oracle, SQL Server, PostgreSQL, MySQL, and H2 (an in-memory database frequently used for testing and development).

Learn Java basics with our Java training in Chennai.

Object-Relational Mapping and Hibernate

An object-relational mapping (ORM) framework is called Hibernate. Let’s examine what that entails and its significance.

  • Entities: Creating the Java classes that will be mapped to database tables is known as entity definition. Usually, @Entity is used to annotate these.
  • Mapping Annotations: Learning how to use important annotations such as @Id, @GeneratedValue, @Column, and @Table to map class properties to table columns and primary keys is known as mapping annotations.
  • Data Types Mapping: Knowing how Java data types are mapped to database column types is known as data types mapping.
Key Concepts of ORM and Hibernate:
  • Mapping: You can specify how your Java classes (entities) are mapped to database tables using Hibernate.
  • Persistence: Hibernate manages the process of getting data from the database as Java objects and saving (persisting) your Java objects to the database.
  • Abstraction: Hibernate removes the underlying database details through abstraction.
  • Object-Oriented Interaction: Working directly with Java objects and their relationships (such as many-to-many, one-to-many, and one-to-one) is known as object-oriented interaction. These object operations are converted into the required database operations by Hibernate.

By adding a layer of abstraction between your object model and the relational database, Hibernate makes database interactions in Java applications easier. By managing the intricacies of mapping, persistence, and SQL generation, it frees you up to concentrate on developing your application’s essential features.

Recommended: Oracle SQL training in Chennai.

Hibernate SessionFactory and Session

Two essential interfaces for working with the database in Hibernate are SessionFactory and Session. 

SessionFactory:

Creating Session objects is the responsibility of a heavyweight, thread-safe object called a SessionFactory. It is created once when the application first launches.

  • It contains information on how your database tables and Java classes are mapped.
  • It manages the second-level cache in Hibernate, which is optional but can significantly increase performance.
Role:
  • To manage and create Session objects.
  • To keep configuration data in storage.
  • To offer a thread-safe, worldwide entry point for acquiring Session instances.
Lifecycle:
  • Created once when the application first launches.
  • Stays in use for the duration of the application.
  • Closed after the program terminates.

Analogy: Consider SessionFactory to be the auto factory (Sessions). It’s an intricate structure that is only built up once.

Session:

A lightweight, single-threaded object called a session is used to represent a database work unit. For carrying out CRUD (Create, Read, Update, Delete) operations on persistent objects, it offers the main interface. It oversees the first-level cache, which is crucial to Hibernate’s operation.

Role:
  • To communicate with the database on the application’s behalf.
  • To preserve and recover information.
  • To oversee transactions.
Lifecycle:
  • Produced on demand, usually at the start of a project or transaction.
  • Closed following the completion of the work unit or the transaction.
  • A single SessionFactory can be used to create several Session instances.

Analogy: Consider a session as a factory-made automobile. You return it (close it) after using it for a particular journey (transaction).

FeatureSessionFactorySession
Thread SafetyThread-Safe.Not Thread-Safe.
WeightHeavyweight.Lightweight.
LifecycleApplication-Level.Transaction/Unit of work level.
PurposeCreate Sessions and Stores Metadata.Interacts with the database and manages persistence.
ScopeOne per database.Multiple per application.

Example Code:

// 1. Build the SessionFactory (usually done once)

SessionFactory sessionFactory = new Configuration()

    .configure(“hibernate.cfg.xml”) // Load configuration

    .buildSessionFactory();

// 2. Open a Session (done for each transaction)

Session session = sessionFactory.openSession();

Transaction transaction = null;

try {

    // 3. Begin a transaction

    transaction = session.beginTransaction();

    // 4. Perform database operations using the Session

    MyEntity myEntity = new MyEntity();

    session.save(myEntity); // Save an object

    MyEntity loadedEntity = session.get(MyEntity.class, 1L); // Load an object

    // 5. Commit the transaction

    transaction.commit();

} catch (Exception e) {

    if (transaction != null) {

        transaction.rollback(); // Rollback on error

    }

    e.printStackTrace(); // Handle the exception

} finally {

    // 6. Close the Session (always close it in a finally block)

    session.close();

}

// 7. Close the SessionFactory when the application ends

// sessionFactory.close();

Related Training: Spring Course in Chennai.

CRUD Operations in Hibernate

Hibernate’s CRUD operations are the essential building blocks for using this potent ORM framework to interact with your database. Let’s examine how the Create, Read, Update, and Delete operations are handled by Hibernate.

Create (New Entities)

To add a new record to your database table with Hibernate, you must first create an instance of your mapped entity class and then use the Session interface to save it.

// Assuming you have a User entity class mapped to a ‘users’ table

User newUser = new User();

newUser.setUsername(“john.doe”);

newUser.setEmail(“john.doe@example.com”);

// Get the current Hibernate Session

Session session = sessionFactory.openSession();

Transaction transaction = null;

try {

    transaction = session.beginTransaction();

    // Persist the new entity to the database

    session.persist(newUser);

    transaction.commit();

    System.out.println(“User saved successfully!”);

} catch (Exception e) {

    if (transaction != null) {

        transaction.rollback();

    }

    e.printStackTrace();

} finally {

    session.close();

}

Read (Retrieving Entities)

Hibernate offers multiple methods for retrieving information from your database:

An entity can be retrieved using session.get(EntityType.class, primaryKey) by using its primary key. It returns null if there is no entity with the specified ID.

Session session = sessionFactory.openSession();

try {

    User user = session.get(User.class, 1L); // Assuming User has a Long primary key

    if (user != null) {

        System.out.println(“Retrieved user: ” + user.getUsername());

    } else {

        System.out.println(“User with ID 1 not found.”);

    }

} finally {

    session.close();

}

Update (Modifying Existing Entities)

Retrieving the entity from the database, changing its state, and finally using the session are the steps involved in updating an existing record.update() or allow it to be handled within a transaction by Hibernate’s automatic dirty checking.

Session session = sessionFactory.openSession();

Transaction transaction = null;

try {

    transaction = session.beginTransaction();

    // Retrieve the entity you want to update

    User user = session.get(User.class, 1L);

    if (user != null) {

        // Modify the entity’s state

        user.setEmail(“new.email@example.com”);

        // Option 1: Explicitly update the entity

        // session.update(user);

        // Option 2: Automatic dirty checking (if the entity is still attached to the session)

        // Hibernate will detect the changes when the transaction is committed.

        transaction.commit();

        System.out.println(“User updated successfully!”);

    } else {

        System.out.println(“User with ID 1 not found for update.”);

    }

} catch (Exception e) {

    if (transaction != null) {

        transaction.rollback();

    }

    e.printStackTrace();

} finally {

    session.close();

}

Delete (Removing Entities)

To delete an entity, use the session.delete() method after getting it from the database.

Session session = sessionFactory.openSession();

Transaction transaction = null;

try {

    transaction = session.beginTransaction();

    // Retrieve the entity you want to delete

    User userToDelete = session.get(User.class, 1L);

    if (userToDelete != null) {

        // Delete the entity

        session.delete(userToDelete);

        transaction.commit();

        System.out.println(“User deleted successfully!”);

    } else {

        System.out.println(“User with ID 1 not found for deletion.”);

    }

} catch (Exception e) {

    if (transaction != null) {

        transaction.rollback();

    }

    e.printStackTrace();

} finally {

    session.close();

}

Hibernate allows you to work with Java objects, which makes database interactions easier. Your key tool for carrying out these CRUD tasks is the Session interface, and data integrity depends on your ability to comprehend transactions.

Recommended: Advanced Java Training in Chennai.

Hibernate Query Language (HQL)

Similar in syntax to SQL, Hibernate Query Language (HQL) is an object-oriented query language that works with persistent objects and their properties rather than tables and columns. These HQL queries are then converted by Hibernate into normal SQL that is tailored to your selected database.

Session session = sessionFactory.openSession();

try {

    List<User> users = session.createQuery(“FROM User WHERE username = :name”, User.class)

 .setParameter(“name”, “john.doe”)

.list();

    for (User user : users) {

        System.out.println(“Found user via HQL: ” + user.getUsername());

    }

} finally {

    session.close();

}

One of Hibernate’s most effective tools is HQL. It enables object-oriented database interaction, which improves the readability and maintainability of your data access code. You can effectively obtain, edit, and remove data based on your entity model by being aware of its syntax and capabilities.

Criteria API in Hibernate

Instead of expressing HQL as strings, the Criteria API uses Java objects to programmatically create database queries in Hibernate. Imagine using a type-safe, fluid API to build your queries piece by piece. When creating dynamic queries, where the filtering conditions may change at runtime, this might be quite helpful. 

Review your skills with Hibernate Interview Questions and Answers.

Core Components of Criteria API

You will mostly use these APIs to work with the Criteria API:

  • CriteriaBuilder: Predicates (conditions), orderings, criteria query objects, and other query components are all created using the CriteriaBuilder factory. The Session provides you with an instance.
  • CriteriaQuery<T>: Indicates the entity type (T) that the query will return and represents a type-safe root query object.
  • Root<T>: Denotes the entity in the FROM clause, which is the root entity in your query. Its associations and attributes are navigable.
  • Predicate: Indicates a condition that is applied in your query’s WHERE clause. The CriteriaBuilder is used to generate predicates.
  • Order: In the ORDER BY clause, this is an ordering phrase. The CriteriaBuilder is used to generate orderings.
  • Selection<T>: Indicates what you wish to choose, such as the entity, particular characteristics, or total values.

Example:

Session session = sessionFactory.openSession();

try {

    CriteriaBuilder builder = session.getCriteriaBuilder();

    CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);

    Root<User> root = criteriaQuery.from(User.class);

    criteriaQuery.select(root); // Select the root entity (optional, defaults to root)

    List<User> users = session.createQuery(criteriaQuery).list();

    for (User user : users) {

        System.out.println(user.getUsername());

    }

} finally {

    session.close();

}

A type-safe and programmatic method for creating database queries in Hibernate is offered by the Criteria API. When creating dynamic queries with unknown circumstances at compile time, it is especially helpful.

Relationships (Associations) in Hibernate

Here are the relationships in Hibernate:

  • One-to-One: Mapping one-to-one relationships between things. such as @OneToOne annotations.
  • One-to-Many / Many-to-One: Mapping entities with one-to-many or many-to-one relationships is known as one-to-many/many-to-one mapping. annotations such as @JoinColumn, @ManyToOne, and @OneToMany.
  • Many-to-Many: Utilizing a join table to map entities with many-to-many relationships. annotations such as @JoinTable and @ManyToMany.
  • Eager vs. Lazy Loading: Being aware of the performance effects and how linked things are loaded from the database.

Suggested: J2EE training in Chennai.

Transactions Management in Hibernate

Hibernate offers two popular approaches for transaction management:

  • Programmatic Transaction Management: With this method, you control the transaction boundaries in your code explicitly. A transaction is initiated, database actions are carried out, and depending on the results, the transaction is either committed or rolled back.
  • Declarative Transaction Management: With this method, a container uses configuration to manage transactions. Transactions can be started, committed, and rolled back without explicit code. Using the rules that have been specified, the container controls the transaction lifecycle.
Best Practices for Transaction Management in Hibernate:
  • Always Use Transactions for Data Modification
  • Keep Transactions Short
  • Handle Exceptions Properly
  • Close Sessions
  • Understand Isolation Levels
  • Prefer Declarative Transaction Management (When Applicable)

Caching in Hibernate

A key component of improving your data access layer’s performance is caching. Hibernate may drastically cut down on costly database round trips by keeping frequently visited data in memory, which improves application response times and lowers database load. 

  • First-Level Cache (Session Cache): One Hibernate Session instance is linked to the first-level cache. This in-memory cache is required and activated by default.
  • Second-Level Cache (SessionFactory Cache): It is linked to the SessionFactory and is shared by all Session instances that the SessionFactory creates. It must be specifically set up and activated because it is an optional cache.

Caching is most effective for:

  • Data that is accessed far more frequently than it is altered is referred to as frequently read data.
  • Data that doesn’t change very often is referred to as relatively static data.
  • Application components that are key to performance: Where speeding up response times and lowering database load are crucial.

Inheritance Mapping in Hibernate

When you need to persist inheritance hierarchies from your object model into your relational database, inheritance mapping becomes a fascinating topic. 

  • There are multiple ways to link these inheritance relationships to database columns using Hibernate. 
  • Every approach has different trade-offs with regard to query complexity, performance, and data standardization.

Table per Class Hierarchy (TPCH) / Single Table Strategy: Every class in the inheritance tree is mapped to a single database table using the table per class hierarchy (TPCH) or single table strategy. To determine the kind of record (which subclass the row represents), a discriminator column is utilized. In rows that represent other subclasses, subclass-specific columns are nullable.

Table per Subclass (TPS) / Joined Strategy: In the inheritance hierarchy, every concrete subclass has a database table associated with it. Only the subclass-specific columns are present in each subclass’s table, together with a foreign key column that points to the base class’s table’s primary key. The shared attributes are usually mapped to a separate table for the base class.

Table per Concrete Class (TPCC) / Union Subclass Strategy: In the inheritance hierarchy, every concrete class is mapped to a separate table. Every concrete class’s attributes, including those inherited from its superclasses, are listed in the table for that class. The abstract superclass (if any) has no table.

Choosing the Right Strategy:

A number of variables determine the optimal inheritance mapping approach:

  • TPCH is ideal for query frequency over the entire hierarchy.
  • The optimal level of data normalization is provided by TPS.
  • TPCC is effective at determining the frequency of querying particular subclasses.
  • Number of common versus subclass-specific characteristics: TPCH may result in a large number of nullable columns if there are a lot of subclass-specific attributes.
  • Performance specifications for various query types: Compare the costs of UNION ALL (TPCC) with joins (TPS).
  • Regularity of common attribute updates: TPCC may be more expensive for some modifications.

You can map inheritance hierarchies to your database in a variety of ways with Hibernate. Designing an effective and maintainable data model that fits the needs of your application and query patterns requires an understanding of the trade-offs associated with each method (Single Table, Joined Table, and Table per Concrete Class).

Interceptors and Listeners in Hibernate
  • Interceptors: These enable you to execute custom logic and intercept hibernate events, including loading, saving, and deleting.
  • Listeners: Like interceptors, listeners offer a more organized method of reacting to particular Hibernate events.

Explore All Software Training Courses Here

Conclusion

Hibernate Framework Tutorial, we have explored from configuring the environment and defining our entities to carrying out CRUD operations, creating complex queries using HQL and the Criteria API, and overseeing complex relationships between our domain objects. Hone your Java development skills with real-time Hibernate project examples in our Hibernate training in Chennai.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.