How to Generate UUIDs as Primary Keys with Hibernate

Using UUIDs (Universally Unique Identifiers) as primary keys in Hibernate ensures globally unique identifiers across distributed systems. In this tutorial, we will create a simple example using Hibernate 6 to generate UUIDs as primary keys.


  1. Java Development Kit (JDK) 21 or higher: Ensure JDK is installed and configured in your system.
  2. Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or any other IDE.
  3. Maven: Ensure Maven is installed and configured in your system.

Step 1: Create a Maven Project

  1. Open your IDE and create a new Maven project.
  2. Update the pom.xml file to include Hibernate and other required dependencies.
<project xmlns=""



  • Hibernate Core Dependency: Includes the main Hibernate framework.
  • SLF4J Dependencies: Used for logging.
  • H2 Database Dependency: An in-memory database for testing purposes.

Step 2: Create Hibernate Configuration File

Create a file named hibernate.cfg.xml in the src/main/resources directory.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "">
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>
        <property name="">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>


  • Dialect: Specifies the SQL dialect (H2 in this case).
  • Connection Properties: Configure the JDBC connection to the H2 database.
  • Automatically manages the database schema (update existing schema).
  • show_sql: Prints SQL statements to the console.
  • format_sql: Formats SQL statements.

Step 3: Create the Employee Entity Class with UUID as the Primary Key

Create a package named com.example.entity and a class named Employee.

package com.example.entity;

import jakarta.persistence.*;
import java.util.UUID;

public class Employee {

    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    private String name;
    private String department;

    public Employee() {}

    public Employee(String name, String department) { = name;
        this.department = department;

    public UUID getId() {
        return id;

    public void setId(UUID id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getDepartment() {
        return department;

    public void setDepartment(String department) {
        this.department = department;

    public String toString() {
        return "Employee{id=" + id + ", name='" + name + '\'' + ", department='" + department + '\'' + '}';


  • @Id: Marks the field as the primary key.
  • @GeneratedValue: Specifies the strategy for generating values for the primary key.
  • @GenericGenerator: Configures a custom generator (UUID generator in this case).

Step 4: Create Hibernate Utility Class

Create a package named com.example.util and a class named HibernateUtil.

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);

    public static SessionFactory getSessionFactory() {
        return sessionFactory;


  • Configuration: Loads Hibernate configuration from hibernate.cfg.xml.
  • ServiceRegistry: Builds the service registry from the configuration settings.
  • SessionFactory: Provides sessions to interact with the database.

Step 5: Create Main Class

Create a package named com.example and a class named Main.

package com.example;

import com.example.entity.Employee;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.UUID;

public class Main {
    public static void main(String[] args) {
        // Save a new employee
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Employee employee = new Employee("John Doe", "IT");;

        // Retrieve the employee
        session = HibernateUtil.getSessionFactory().openSession();
        Employee retrievedEmployee = session.get(Employee.class, employee.getId());
        System.out.println("Retrieved Employee: " + retrievedEmployee);

        // Close the SessionFactory


  • Session: Opens a session to interact with the database.
  • Transaction: Begins and commits a transaction for database operations.
  • Save: Persists the entity to the database.
  • Retrieve: Fetches the entity from the database using its UUID.

Step 6: Run the Application

  1. Run the Main class.
  2. The output in the console should be:
Hibernate: create table Employee (id binary(255) not null, department varchar(255), name varchar(255), primary key (id))
Hibernate: insert into Employee (id, department, name) values (?, ?, ?)
Hibernate: select as id1_0_0_, employee0_.department as departme2_0_0_, as name3_0_0_ from Employee employee0_ where
Retrieved Employee: Employee{id=<UUID>, name='John Doe', department='IT'}


You have successfully created an example using Hibernate 6 to generate UUIDs as primary keys. This tutorial covered setting up a Maven project, configuring Hibernate, creating an entity class with a UUID primary key, and performing basic CRUD operations to observe the automatic generation and handling of UUIDs.