Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

UUID is a relatively common type of primary key used in databases. It’s practically globally unique, which makes it a good choice for ID type in distributed systems.

In this tutorial, we’ll take a look at how we can leverage Hibernate and JPA to generate UUIDs for our entities.

2. JPA/Jakarta Specification

First, we’ll take a look at what JPA provides to address this.

Since version 3.1.0, which came out in 2022, the JPA specification provides developers with a new GenerationType.UUID we can use in the @GeneratedValue annotation:

@Entity
class Reservation {

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

    private String status;

    private String number;

    // getters and setters
}

GenerationType instructs that a UUID for the entity should be generated automatically for us by the persistence provider.

Hibernate, in particular, supports JPA 3.1.0 from version 6.2. So, having at least Hibernate 6.2, this would work:

@Test
public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUID() throws IOException {
    Reservation reservation = new Reservation();
    reservation.setStatus("created");
    reservation.setNumber("12345");
    UUID saved = (UUID) session.save(reservation);
    Assertions.assertThat(saved).isNotNull();
}

However, in RFC 4122, there are four types/versions of UUID defined. And JPA specification leaves the choice of UUID version to the persistence provider. So different persistence providers may generate UUIDs of different versions.

By default, Hibernate generates UUIDs of the 4th version:

@Test
public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUIDOfVersion4() throws IOException {
    Reservation reservation = new Reservation();
    reservation.setStatus("new");
    reservation.setNumber("012");
    UUID saved = (UUID) session.save(reservation);
    Assertions.assertThat(saved).isNotNull();
    Assertions.assertThat(saved.version()).isEqualTo(4);
}

In terms of RFC 4122, Hibernate is capable of creating UUIDs of two versions — 1 and 4. We’ll see how we can generate time-based (version 1) UUIDs later.

3. Prior to Hibernate 6.2

In some projects, it might be not possible to jump from JPA specification 2.x to JPA (or Jakarta) specification 3.1.0. However, if we have Hibernate version 4 or 5, we still have the ability to generate UUIDs. For that, we have two approaches.

First, we can achieve this by specifying the org.hibernate.id.UUIDGenerator class in the @GenericGenerator annotation:

@Entity
class Sale {

    @Id
    @GeneratedValue(generator = "uuid-hibernate-generator")
    @GenericGenerator(name = "uuid-hibernate-generator", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;

    private boolean completed;

    //getters and setters
}

And the behavior will be the same as in Hibernate 6.2:

@Test
public void whenGeneratingUUIDUsingGenericConverter_thenAlsoGetUUIDGeneratedVersion4() throws IOException {
    Sale sale = new Sale();
    sale.setCompleted(true);
    UUID saved = (UUID) session.save(sale);
    Assertions.assertThat(saved).isNotNull();
    Assertions.assertThat(saved.version()).isEqualTo(4);
}

However, this approach is quite verbose, and we can get identical behavior by just using the org.hibernate.annotations.UuidGenerator annotation:

@Entity
class Sale {

    @Id
    @UuidGenerator
    private UUID id;

    private boolean completed;

    // getters and setters 
}

Furthermore, when specifying @UuidGenerator, we can choose the concrete version of UUID to generate. This is defined by the style parameter. Let’s see the values that this parameter can take:

  • RANDOM – generate UUID based on random numbers (version 4 in RFC)
  • TIME – generate time-based UUID (version 1 in RFC)
  • AUTO – this is the default option and is the same as RANDOM

Let’s see how we can control the version of the UUID generated by Hibernate:

@Entity
class WebSiteUser {

    @Id
    @UuidGenerator(style = UuidGenerator.Style.TIME)
    private UUID id;

    private LocalDate registrationDate;

    // getters and setters
}

And now, as we may check, Hibernate will generate time-based (version 1) UUIDs:

@Test
public void whenGeneratingTimeBasedUUID_thenUUIDGeneratedVersion1() throws IOException {
    WebSiteUser user = new WebSiteUser();
    user.setRegistrationDate(LocalDate.now());
    UUID saved = (UUID) session.save(user);
    Assertions.assertThat(saved).isNotNull();
    Assertions.assertThat(saved.version()).isEqualTo(1);
}

4. String as UUID

Also, Hibernate is intelligent enough to generate UUIDs for us if we use String as the Java ID type:

@Entity
class Element {

    @Id
    @UuidGenerator
    private String id;

    private String name;
}

As we can see, Hibernate can handle both String and UUID Java types:

@Test
public void whenGeneratingUUIDAsString_thenUUIDGeneratedVersion1() throws IOException {
    Element element = new Element();
    element.setName("a");
    String saved = (String) session.save(element);
    Assertions.assertThat(saved).isNotEmpty();
    Assertions.assertThat(UUID.fromString(saved).version()).isEqualTo(4);
}

Here, we should note that when we set a column to have type java.util.UUID, Hibernate tries to map it to the corresponding UUID type in the database. This type can differ from one database to another.

So, the exact type practically depends on the Hibernate dialect set. For instance, if we’re using PostgreSQL, then the corresponding type will be UUID in PostgreSQL. If we’re using Microsoft SQL Server, then the corresponding type will be UNIQUEIDENTIFIER. However, if we use String as the Java ID type, then Hibernate maps it into some SQL textual type, such as TEXT or VARCHAR.

5. Conclusion

In this article, we learned different ways to generate UUIDs with Hibernate.

There were several options to do it prior to Jakarta 3.1.0 specification and Hibernate 6.2. And as of Hibernate 6.2, we can use the new JPA GenerationType.UUID to generate UUIDs independently from the persistence provider.

However, the JPA specification doesn’t specify the version of the UUID generated. If we want to specify a concrete version, we need to use Hibernate-specific classes, and we still have two options — version 1 or version 4.

As always, the source code for this tutorial is available over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.