PostgreSQL Java Tutorial: Connect to PostgreSQL with Hibernate

December 10, 2023

Summary: in this tutorial, we will discuss how to connect PostgreSQL with Hibernate in Java.

Table of Contents

What is Hibernate?

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.

Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from 95% of common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Hibernate Position

Hibernate Advantages

  • Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.
  • Provides simple APIs for storing and retrieving Java objects directly to and from the database.
  • If there is change in the database or in any table, then you need to change the XML file properties only.
  • Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.
  • Hibernate does not require an application server to operate.
  • Manipulates Complex associations of objects of your database.
  • Minimizes database access with smart fetching strategies.
  • Provides simple querying of data.

To connect Hibernate with PostgreSQL, you need to follow these steps:

Add the necessary dependencies

Include the Hibernate and PostgreSQL dependencies in your project’s build configuration. If you’re using Maven, add the following dependencies to your pom.xml file:

<dependencies>
 <! - Hibernate >
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>{hibernate-version}</version>
 </dependency>
 
 <! - PostgreSQL >
 <dependency>
 <groupId>org.postgresql</groupId>
 <artifactId>postgresql</artifactId>
 <version>{postgresql-version}</version>
 </dependency>
</dependencies>

Replace {hibernate-version} and {postgresql-version} with the appropriate versions you want to use.

Configure Hibernate properties

Create a Hibernate configuration file (e.g., hibernate.cfg.xml) and specify the PostgreSQL database connection properties. Here’s an example configuration:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
 <! - Database connection properties >
 <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
 <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/your_database</property>
 <property name="hibernate.connection.username">your_username</property>
 <property name="hibernate.connection.password">your_password</property>
 
 <! - Other Hibernate properties >
 <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
 <property name="hibernate.show_sql">true</property>
 <property name="hibernate.format_sql">true</property>

 <! first time it is create and then onwards update>
 <property name="hbm2ddl.auto">update</property>
 
 <! - Mapping files or annotated classes >
 <! - Add your entity classes or mapping files here  for ex: entity used below >
 <mapping class="org.demo.main.model.Employee"/>
 
 </session-factory>
</hibernate-configuration>

Replace your_database, your_username, and your_password with your actual database name, username, and password, respectively.

Create entity classes

Define your entity classes that represent the database tables. Annotate the classes and their properties with appropriate Hibernate annotations to map them to the corresponding database tables and columns.

For example:

@Entity
@Table(name = "employees")
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 
 @Column(name = "name")
 private String name;
 
 // Getters and setters, constructors, etc.
}

Use Hibernate APIs

In your code, you can now use Hibernate APIs to interact with the database using the defined entity classes. For example, you can use SessionFactory and Session to perform database operations.

Here’s an example of how to retrieve all employees from the database:

SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
List<Employee> employees = session.createQuery("FROM Employee", Employee.class).getResultList();
for (Employee employee : employees) {
 System.out.println("ID: " + employee.getId() + ", Name: " + employee.getName());
}
transaction.commit();
session.close();
sessionFactory.close();

Make sure to handle exceptions, close sessions, and manage transactions properly in your application.

That’s it! With these steps, you should be able to connect Hibernate with PostgreSQL and perform database operations using Hibernate APIs.