Generate UUIDs in Java
How to generate UUIDs in Java: java.util.UUID methods, v4 and v3 built-in support, v7 generation, and Hibernate/JPA integration with code examples.
Detailed Explanation
Java has built-in UUID support through java.util.UUID, which has been available since Java 5. However, the standard library only supports v3 (name-based MD5) and v4 (random) directly. For v7, you need either Java 21+ or a third-party library.
UUID v4 (random):
import java.util.UUID;
UUID id = UUID.randomUUID();
System.out.println(id); // e.g., 550e8400-e29b-41d4-a716-446655440000
System.out.println(id.version()); // 4
System.out.println(id.variant()); // 2 (RFC 4122)
System.out.println(id.getMostSignificantBits());
System.out.println(id.getLeastSignificantBits());
UUID v3 (name-based MD5):
// Java only provides nameUUIDFromBytes (v3, no namespace parameter)
UUID id = UUID.nameUUIDFromBytes("example.com".getBytes());
System.out.println(id.version()); // 3
Note: Java's nameUUIDFromBytes does not accept a namespace UUID. It directly hashes the input bytes with MD5. For proper v5 (SHA-1) with namespace support, use a library like com.github.f4b6a3:uuid-creator.
UUID v7 (Java 21+ or library):
// Java 21+ (JEP proposal, check current status)
// UUID id = UUID.timeOrderedRandom(); // Proposed API
// Using uuid-creator library (works on any Java 8+):
// Maven: com.github.f4b6a3:uuid-creator:5.3.7
import com.github.f4b6a3.uuid.UuidCreator;
UUID v7 = UuidCreator.getTimeOrderedEpoch(); // UUID v7
UUID v1 = UuidCreator.getTimeBased(); // UUID v1
UUID v5 = UuidCreator.getNameBasedSha1(UuidCreator.NAMESPACE_DNS, "example.com");
Parsing and validation:
// Parse from string
UUID id = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
// Validation (fromString throws IllegalArgumentException for invalid input)
try {
UUID.fromString(input);
return true;
} catch (IllegalArgumentException e) {
return false;
}
Hibernate/JPA integration:
import jakarta.persistence.*;
import java.util.UUID;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id; // Hibernate 6.2+ generates v4 by default
// For v7, use a custom generator:
@Id
@GenericGenerator(name = "uuid7", type = UuidV7Generator.class)
@GeneratedValue(generator = "uuid7")
private UUID id;
}
Performance considerations: UUID.randomUUID() in Java uses SecureRandom, which can block on Linux if /dev/random is exhausted. In high-throughput scenarios, configure the JVM to use /dev/urandom by setting -Djava.security.egd=file:/dev/./urandom. Modern Linux kernels (5.6+) have eliminated the blocking behavior, making this less of a concern.
Sorting caveat: Java's UUID.compareTo() compares the most significant bits first as signed long values. This means UUIDs do not sort in the same order as their string representations. For correct lexicographic sorting, compare the string forms or use unsigned comparison.
Use Case
Java UUID generation is fundamental in Spring Boot microservices for creating entity identifiers, distributed tracing correlation IDs, and Kafka message keys for partitioned topic ordering.