Difficulty: Beginner
Estimated Time: 10

This tutorial walks through the steps of creating a bare-bones Java application which connects to a PostgreSQL database, then stores and retrieves data using Hibernate. It will demonstrate:

  • Configuring Hibernate to connect to PostgreSQL via JDBC
  • Creating JPA Entities
  • Storing data contained in JPA Entities in PostgreSQL
  • Retrieving data contained in JPA Entities from PostgreSQL

There you have it, the essence of a Hibernate <-> PostgreSQL connection. Of course, things get a lot more interesting once there are more classes and relations involved...

Connecting to PostgreSQL with Java and Hibernate

Step 1 of 6

Application build configuration

The core Hibernate library has numerous dependencies on other libraries. While you could obtain and install all of them manually, this is a tedious and error-prone process; fortunately, tools such as Maven and Gradle exist to ease the burden by automatically downloading and installing these libraries.

For this tutorial, we'll use Gradle, a build tool that includes a robust dependency-management system. Gradle is already installed in this environment; to obtain Gradle for your own system, visit gradle.org.

Gradle operates based on the notion of "tasks" which can be performed on a build. Out of the box, several tasks are predefined - you can list them by running the "tasks" task:

gradle tasks

We can use the "init" task to create an initial build configuration for our application:

gradle init --type java-application --package com.example.hibernateconnect --project-name hibernateconnect --test-framework junit --dsl groovy

The options here specify the type of project we're building (a Java application), a name for the Java packages, a name for the project, a testing framework to use, and a language for the build scripts themselves (we'll use Groovy, which is the default for Gradle). If you omit options, Gradle will prompt you for them interactively.

This creates a set of configuration files, source files, and a shell script named gradlew known as the Wrapper that we'll use in place of the gradle command for future interactions with Gradle. Once this wrapper has been generated, the project can be built on other machines without requiring an installation of Gradle first, and avoids problems that might arise if the installed version does not match across machines.

Test the Wrapper by running:

./gradlew --version