Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active March 2, 2024 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiolimace/69429ea8e86460de316c79bf6290f93a to your computer and use it in GitHub Desktop.
Save fabiolimace/69429ea8e86460de316c79bf6290f93a to your computer and use it in GitHub Desktop.
Strongly Typed Identifier using ULID Creator
package com.example.idapi;
import java.util.Objects;
import com.github.f4b6a3.ulid.Ulid;
import com.github.f4b6a3.ulid.UlidCreator;
public abstract class Id<T extends Id<T>> implements Comparable<T> {
protected final Ulid value;
public Id() {
this.value = UlidCreator.getMonotonicUlid();
}
public Id(Ulid value) {
Objects.requireNonNull(value);
this.value = value;
}
public Id(String string) {
Objects.requireNonNull(string);
this.value = Ulid.from(string);
}
public Ulid toUlid() {
return this.value;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass() != getClass())
return false;
return this.value.equals(((T) other).value);
}
@Override
public int compareTo(T other) {
return this.value.compareTo(other.value);
}
@Override
public String toString() {
return String.format("%s{value=%s}", getClass().getSimpleName(), value);
}
}
package com.example;
import com.github.f4b6a3.ulid.Ulid;
public final class UserId extends Id<UserId> {
public UserId() {
super();
}
public UserId(Ulid value) {
super(value);
}
public UserId(String string) {
super(string);
}
public static UserId of(Ulid value) {
return new UserId(value);
}
public static UserId of(String string) {
return new UserId(string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment