Hibernate Configuration Tutorial with Complete Example using PostgreSQL

 In this session, we will walk through the setup and configuration of Hibernate using annotations for a PostgreSQL database. This will include setting up the project, configuring Hibernate, and performing CRUD operations.

Prerequisites:

  1. Java 8+ installed on your machine.
  2. PostgreSQL installed and running on your system.
  3. Maven or Gradle for dependency management.
  4. IDE like IntelliJ IDEA or Eclipse.

1. Set Up Project

Add Dependencies to pom.xml

Ensure that the necessary dependencies are added to your pom.xml file for Hibernate, PostgreSQL, and JPA.

<dependencies>

<!-- JPA API -->

<dependency>

<groupId>jakarta.persistence</groupId>

<artifactId>jakarta.persistence-api</artifactId>

<version>3.1.0</version>

</dependency>


<!-- Hibernate JPA Implementation -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>6.3.0.Final</version>

</dependency>


<!-- Postgresql Driver -->

<dependency>

<groupId>org.postgresql</groupId>

<artifactId>postgresql</artifactId>

<version>42.5.0</version>

</dependency>

</dependencies>


2. Hibernate Configuration File (hibernate.cfg.xml)

Create the hibernate.cfg.xml file in the src/main/resources directory. This file contains the Hibernate configuration settings.


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- JDBC Database connection settings --> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="hibernate.driver_class">org.postgresql.Driver</property> <property name="hibernate.url">jdbc:postgresql://localhost:5432/hibernate_example</property> <property name="hibernate.username">postgres</property> <property name="hibernate.password">your_password_here</property> <!-- JDBC connection pool settings --> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <!-- Specify dialect --> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="hibernate.current_session_context_class">thread</property> <!-- Echo all executed queries --> <property name="hibernate.show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Disable the second-level cache --> <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="hibernate.format_sql">true</property> </session-factory> </hibernate-configuration>

Explanation:

  • hibernate.dialect: Specifies the dialect for PostgreSQL (PostgreSQLDialect).
  • hibernate.url: The JDBC URL for connecting to PostgreSQL (jdbc:postgresql://localhost:5432/hibernate_example).
  • hibernate.username and hibernate.password: Database connection credentials.
  • hibernate.hbm2ddl.auto: Specifies how Hibernate handles schema generation (update for automatic updates).
  • hibernate.show_sql: Enables the logging of executed SQL queries.

3. Create Entity Class (Employee)

The entity class will represent the table in the PostgreSQL database. Let's define an Employee entity class using Hibernate annotations.


import jakarta.persistence.*; @Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "salary") private Double salary; // Default constructor public Employee() {} // Constructor with parameters public Employee(String name, Double salary) { this.name = name; this.salary = salary; } // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]"; } }

Annotations Used:

  • @Entity: Marks this class as a Hibernate entity.
  • @Table: Specifies the table in the database (employee).
  • @Id: Marks the primary key of the entity.
  • @GeneratedValue: Indicates the auto-generation strategy for the primary key (GenerationType.IDENTITY is used for auto-increment).
  • @Column: Specifies the mapping between the entity field and the table column.

4. Hibernate Utility Class

This utility class will provide the SessionFactory and manage the session lifecycle.

import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static { try { // Create SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Employee.class) .buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); throw new ExceptionInInitializerError("Initial SessionFactory creation failed." + e); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } }

Explanation:

  • The SessionFactory is configured using the hibernate.cfg.xml file.
  • The addAnnotatedClass method registers the Employee entity.
  • getSessionFactory() returns the SessionFactory, and shutdown() closes it when the application ends.

5. Main Application to Perform CRUD Operations

Now, let's implement the main class to perform CRUD operations on the Employee table.


import org.hibernate.Session; import org.hibernate.Transaction; public class HibernateExample { public static void main(String[] args) { // Create a session Session session = HibernateUtil.getSessionFactory().openSession(); // 1. Create a new employee and save it Employee employee = new Employee("John Doe", 60000.0); // Start a transaction Transaction transaction = session.beginTransaction(); // Save the employee object session.save(employee); // Commit the transaction transaction.commit(); System.out.println("Employee saved: " + employee); // 2. Retrieve the employee based on ID Employee retrievedEmployee = session.get(Employee.class, employee.getId()); System.out.println("Retrieved employee: " + retrievedEmployee); // 3. Update employee salary transaction = session.beginTransaction(); retrievedEmployee.setSalary(70000.0); session.update(retrievedEmployee); transaction.commit(); System.out.println("Updated employee: " + retrievedEmployee); // 4. Delete the employee transaction = session.beginTransaction(); session.delete(retrievedEmployee); transaction.commit(); System.out.println("Employee deleted: " + retrievedEmployee); // Close session and shutdown session.close(); HibernateUtil.shutdown(); } }

Explanation of CRUD Operations:

  • Create: An Employee instance is created and persisted using session.save().
  • Read: The employee is retrieved by ID using session.get().
  • Update: The employee's salary is updated using session.update().
  • Delete: The employee is deleted using session.delete().

Comments