Skip to content
SimplyMe
Go back

UUIDs vs. ULIDs in Hibernate: Choosing the Right ID Generator

Edit page

When working with Java Hibernate, one of the crucial decisions you’ll make is how to generate primary keys for your entities. Traditionally, auto-incrementing integers have been the go-to choice. However, in modern distributed systems, UUIDs and ULIDs are gaining popularity. Let’s delve into the pros and cons of each, specifically within the context of Hibernate.

UUIDs: The Established Standard

UUIDs (Universally Unique Identifiers) have been around for a long time and are widely supported.

Advantages:

Example Hibernate Entity with UUID:

java @Entity public class Product {     @Id     @GeneratedValue(generator = “uuid2”)     @GenericGenerator(name = “uuid2”, strategy = “org.hibernate.id.UUIDGenerator”)     @Type(type = “uuid-char”)     private UUID id;     // … other fields }

Considerations:

public class ULIDGenerator implements IdentifierGenerator {     @Override     public Object generate(SharedSessionContractImplementor session, Object entity) throws HibernateException {         return ULID.randomULID();     } }

Example Hibernate Entity with ULID: @Entity public class MyEntity {     @Id     @GeneratedValue(generator = “ulidGenerator”)     @GenericGenerator(name = “ulidGenerator”, strategy = “com.example.ULIDGenerator”)     private String id;     // … other fields }

Considerations:


Edit page
Share this post on:

Previous Post
Visualizing Your API with PlantUML: A Diagrammatic Approach
Next Post
Taming the Lazy Beast: Reactive DTOs and Hibernate Relationships in Quarkus