Skip to content

jaspeen/ulid-java

Repository files navigation

ulid-java

CI Maven Central javadoc

Generate and parse ULIDs in Crockford base32 text and binary representations.

See ULID specification for more info

Key points

  • Java 11+
  • API similar to java.util.UUID
  • Optional monotonic generator
  • Optional hibernate type and ID generator (requires hibernate 6.x)

Install

Maven

<dependency>
    <groupId>io.github.jaspeen</groupId>
    <artifactId>ulid-java</artifactId>
    <version>0.2.0</version>
</dependency>

Gradle

dependencies {
    implementation 'io.github.jaspeen:ulid-java:0.2.0'
}

Usage

ULID generation

ULID ulid = ULID.random();
String crockfordBase32 = ulid.toString();
byte[] binary = ulid.toBytes();

Parsing

ULID parsedFromString = ULID.fromString("3ZFXZQYZVZFXZQYZVZFXZQYZVZ");
ULID parsedFromBytes = ULID.fromBytes(
        new byte[] {127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127});
assertEquals(parsedFromString, parsedFromBytes);

UUID compatibility

ULID.random().toUUID();
ULID.fromUUID(UUID.randomUUID());

Monotonic ULID generation

MonotonicULID.random();

Hibernate ID generator

Hibernate is not added as transitive dependency, it should be specified additionally

@Entity
class ULIDEntity {
    @Id
    @GeneratedValue(generator = "ulid")
    @GenericGenerator(name = "ulid", strategy = "io.github.jaspeen.ulid.hibernate.ULIDIdGenerator")
    private ULID id;
}
 
 // This will generate UUID using ULID algorithm providing ordered keys 
 // while keeping other stuff same
@Entity 
class UUIDEntity {
    @Id
    @GeneratedValue(generator = "ulid")
    @GenericGenerator(name = "ulid", strategy = "io.github.jaspeen.ulid.hibernate.ULIDIdGenerator")
    private UUID id;
}

Generator can be defined in package-info.java for all entities instead of field annotation in every entity

@GenericGenerator(name = "ulid", strategy = "io.github.jaspeen.ulid.hibernate.ULIDIdGenerator")
package my.service.model;

import org.hibernate.annotations.GenericGenerator;

Notes

For java 8 and hibernate 5 use verions 0.1.x