Hibernate 6 Example Tutorial

In this tutorial, we will learn how to create Hibernate 6 Application that connects with MySQL using the latest Hibernate 6, Java 17, and MySQL database. We will also take a look into Hibernate 6 features.

Hibernate 6 Overview

Hibernate 6 is the latest version of the popular open-source Object-Relational Mapping (ORM) framework, Hibernate. Hibernate is a tool used by developers to map Java objects to database tables, making it easier to interact with databases using Java code.

Some of the key features and improvements in Hibernate 6 include:

  1. Support for Java 17: Hibernate 6 is compatible with the latest version of Java, which provides better performance, security, and language features.

  2. Improved query performance: Hibernate 6 includes improvements in query performance, making it faster and more efficient when working with large data sets.

  3. Streamlined APIs: Hibernate 6 has simplified APIs, making it easier for developers to use and understand.

  4. Modular architecture: Hibernate 6 has a modular architecture, allowing developers to choose only the modules they need, resulting in smaller and more efficient applications.

  5. Enhanced validation: Hibernate 6 includes enhanced validation capabilities, making it easier to validate data before persisting it to the database.

Hibernate 6 Example Step-By-Step

Let's start developing step by step Hibernate 6 application using Maven as a project management and build tool.

1. Create a Simple Maven Project

You can use either Eclipse IDE or IntelliJ IDEA to create a Maven project.

Use the How to Create a Simple Maven Project in Eclipse article to create a simple Maven project in Eclipse IDE.

Use the How to Create a Simple Maven Project in the IntelliJ IDEA guide to create a simple Maven project in IntelliJ IDEA.

2. Add jar Dependencies to pom.xml

Next, let's add the required dependencies to the pom.xml file:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.7.Final</version>
        </dependency>
Here is the complete pom.xml file for your reference:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>net.javaguides.hibernate</groupId>
        <artifactId>hibernate-tutorial</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>hibernate-6-example</artifactId>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.7.Final</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. Creating the JPA Entity Class(Persistent class)

Let's create a Book persistent class that is mapped to a database "books" table:
package net.javaguides.hibernate.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;

    public Book(){

    }

    public Book(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

4. Create a Hibernate Configuration file - hibernate.cfg.xml

Before creating Hibernate configuration file, make sure that you create a demo database in the MySQL server.
create database demo
Let's create an XML file named hibernate.cfg.xml under the /resources folder and write the following code in it.
<!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>

		<!-- JDBC Database connection settings -->
		<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/demo?useSSL=false</property>
		<property name="connection.username">root</property>
		<property name="connection.password">Mysql@123</property>

		<!-- JDBC connection pool settings ... using built-in test pool -->
		<property name="connection.pool_size">1</property>

		<!-- Echo the SQL to stdout -->
		<property name="show_sql">true</property>

		<!-- Set the current session context -->
		<property name="current_session_context_class">thread</property>

		<!-- Drop and re-create the database schema on startup -->
		<property name="hbm2ddl.auto">create-drop</property>

		<!-- dbcp connection pool configuration -->
		<property name="hibernate.dbcp.initialSize">5</property>
		<property name="hibernate.dbcp.maxTotal">20</property>
		<property name="hibernate.dbcp.maxIdle">10</property>
		<property name="hibernate.dbcp.minIdle">5</property>
		<property name="hibernate.dbcp.maxWaitMillis">-1</property>

		<mapping class="net.javaguides.hibernate.entity.Book" />

	</session-factory>

</hibernate-configuration>
The above configuration file contains information about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml.

In Hibernate 6, we don't have to specify the dialect because Hibernate 6 will automatically configure it based on the database JDBC driver that we add to the classpath.

5. Create a Hibernate Utility Class

Next, let's create a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory.

The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object.
 
Let's create HibernateUtil class to configure singleton SessionFactory and use it throughout the application:
package net.javaguides.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
	private static StandardServiceRegistry registry;
	private static SessionFactory sessionFactory;

	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			try {
				// Create registry
				registry = new StandardServiceRegistryBuilder().configure().build();

				// Create MetadataSources
				MetadataSources sources = new MetadataSources(registry);

				// Create Metadata
				Metadata metadata = sources.getMetadataBuilder().build();

				// Create SessionFactory
				sessionFactory = metadata.getSessionFactoryBuilder().build();

			} catch (Exception e) {
				e.printStackTrace();
				if (registry != null) {
					StandardServiceRegistryBuilder.destroy(registry);
				}
			}
		}
		return sessionFactory;
	}

	public static void shutdown() {
		if (registry != null) {
			StandardServiceRegistryBuilder.destroy(registry);
		}
	}
}

6 Create the main App class and Run an Application

Here is the main App class which is used to connect the MySQL database and persist the Student object in a database table.
package net.javaguides.hibernate;

import java.util.List;

import net.javaguides.hibernate.entity.Book;
import org.hibernate.Session;
import org.hibernate.Transaction;

import net.javaguides.hibernate.util.HibernateUtil;

public class App {
	public static void main(String[] args) {

		Book book = new Book("Core Java", "Learn Core Java with Coding Examples");
		Book book1 = new Book("Learn Hibernate", "Learn Hibernate with building projects");
		Transaction transaction = null;
		try (Session session = HibernateUtil.getSessionFactory().openSession()) {
			// start a transaction
			transaction = session.beginTransaction();
			// save the book objects
			session.persist(book);
			session.persist(book1);
			// commit transaction
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		}

		try (Session session = HibernateUtil.getSessionFactory().openSession()) {
			List<Book> books = session.createQuery("from Book", Book.class).list();
			books.forEach(b -> {
				System.out.println("Print book name : " + b.getName());
			});
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		}
	}
}

Note that we are using Session.persist() method to save the Student entity object into the database.

Output

Conclusion

In this tutorial, we learned how to create Hibernate 6 Application using the latest Hibernate 6 and Java 17. We also looked into Hibernate 6 features.

Comments