Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Your First Hibernate Project

Set up a first Hibernate 7 project step by step with Maven, a hibernate.cfg.xml file, an entity class and a main program, and see the project structure and bootstrap flow.

Time to build something. A minimal Hibernate project has four ingredients: a build file with the right dependencies, a configuration that points at a database, at least one entity class, and a bit of code that bootstraps a SessionFactory and uses a Session. This lesson walks through all four, using Maven and an in-memory H2 database so nothing needs to be installed beyond a JDK.

Hibernate is not available in the in-page runner, so the Maven, XML and Hibernate code below is read-only. The runnable programs are stand-ins: they reproduce the bootstrap flow (reading configuration, opening a connection, running a unit of work inside a transaction) with plain Java and H2, so you see the shape of what Hibernate does.

1. The project layout

TEXT
hibernate-demo/
  pom.xml
  src/main/java/com/example/Book.java
  src/main/java/com/example/Main.java
  src/main/resources/hibernate.cfg.xml
  src/main/resources/log4j2.xml        (optional, for logging)

2. The Maven build

XML
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>hibernate-demo</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>7.4.13.Final</version>      <!-- use the latest 7.x -->
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>2.5.0</version>
    </dependency>
  </dependencies>
</project>

hibernate-core brings the Jakarta Persistence API with it. For another database, swap the H2 dependency for its JDBC driver. Hibernate 7 needs Java 17 or newer. (If you use Spring Boot, you add spring-boot-starter-data-jpa instead and skip most of this lesson; see Spring Boot introduction.)

3. The configuration file

hibernate.cfg.xml on the classpath is Hibernate's native configuration format. We look at every setting in the next chapter; for now:

XML
<?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>
    <property name="hibernate.connection.url">jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1</property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password"></property>

    <property name="hibernate.hbm2ddl.auto">create-drop</property>  <!-- demos only -->
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>

    <mapping class="com.example.Book"/>
  </session-factory>
</hibernate-configuration>

The hbm2ddl.auto setting makes Hibernate create the tables at start-up and drop them at shutdown, which is perfect for a demo and dangerous anywhere else. show_sql prints every statement so you can watch what Hibernate does.

4. The entity

Java
package com.example;

import jakarta.persistence.*;

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;

    private String title;
    private int pages;

    protected Book() {}                       // required by Hibernate (can be protected)

    public Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public int getPages() { return pages; }
}

An entity is an ordinary class with @Entity and an @Id field. Everything else is mapped by convention: the table is Book, the columns are id, title and pages. Details come in Entity mapping.

5. The bootstrap and a first save

Java
package com.example;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        try (SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory()) {

            sessionFactory.inTransaction(session -> {
                session.persist(new Book("Domain-Driven Design", 560));
            });

            sessionFactory.inSession(session -> {
                Book book = session.createSelectionQuery("from Book", Book.class).getSingleResult();
                System.out.println("Loaded " + book.getTitle());
            });
        }
    }
}

new Configuration().configure() reads hibernate.cfg.xml. buildSessionFactory() is the expensive step. inTransaction opens a session, begins a transaction, runs your lambda, commits, and rolls back if the lambda throws. inSession opens a read-only-style session with no transaction around it.

The flow, step by step:

flowchart LR
    A["hibernate.cfg.xml"] --> B["Configuration"]
    B --> C["buildSessionFactory()"]
    C --> D["inTransaction(session -> ...)"]
    D --> E["persist, find, query"]
    E --> F["commit: SQL sent to H2"]

Bootstrap once; do work in short transactions.

Stand-in: configuration to connection

Hibernate reads connection properties and opens JDBC connections from them. This stand-in does the same with a java.util.Properties text and H2, so you can see how a flat property list becomes a live connection.

Java Stand-in: properties to connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: inTransaction

The lambda style of sessionFactory.inTransaction(...) is easy to reproduce. This program builds a tiny inTransaction helper: commit when the lambda finishes, roll back when it throws. Notice that the failed unit of work leaves no trace.

Java Stand-in: commit and rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common first-project problems

  • No default constructor for entity: add a no-argument constructor (it may be protected).
  • Unknown entity / not mapped: the class is missing from <mapping class=.../> (or from addAnnotatedClass).
  • Table not found: you removed hbm2ddl.auto before creating the schema yourself.
  • javax.persistence imports not compiling: Hibernate 6 and later use jakarta.persistence.
  • Silence and no SQL: turn on hibernate.show_sql or the SQL logger category (see Configuration).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Maven artifact brings in Hibernate ORM 7?

    Since version 6 the group ID is org.hibernate.orm, and hibernate-core is the main artifact.
  2. 2. What does sessionFactory.inTransaction(session -> ...) do?

    It opens a Session, begins a transaction, runs the lambda, then commits, or rolls back if the lambda throws.
  3. 3. Why is hibernate.hbm2ddl.auto=create-drop only suitable for demos and tests?

    Dropping the schema at shutdown is fine for throwaway data, but never for real data.
  4. 4. What must every entity class provide for Hibernate?

    Hibernate instantiates entities by reflection, so it needs a no-arg constructor, and it needs an @Id.

Summary

  • A first project needs hibernate-core, a JDBC driver, a configuration, an @Entity and a bootstrap.
  • Configuration().configure().buildSessionFactory() reads hibernate.cfg.xml and builds the heavy shared factory once.
  • inTransaction and inSession run a unit of work with the right session handling.
  • show_sql and hbm2ddl.auto are great for learning, and unsuitable for production defaults.

Next: CRUD with Hibernate