java.util.UUID — the standard library
Java has a built-in UUID class in java.util. It requires no external dependencies — the full API is documented in the Oracle Java 21 docs for java.util.UUID:
import java.util.UUID;
// UUID v4 — random, cryptographically secure
UUID id = UUID.randomUUID();
System.out.println(id); // "550e8400-e29b-41d4-a716-446655440000"
// Parse from string
UUID parsed = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
// Access components
System.out.println(parsed.version()); // 4
System.out.println(parsed.variant()); // 2 (RFC 4122 / RFC 9562 variant)
System.out.println(parsed.toString()); // standard hyphenated form
UUID.randomUUID() uses SecureRandom internally — it is cryptographically secure and RFC 9562-compliant. No new Random() involved.
UUID v7 in Java
The Java standard library does not yet include UUID v7. Two approaches:
Hibernate 6.5+ (recommended for JPA/Spring Boot)
Hibernate 6.5 generates UUID v7 automatically with the TIME style:
import jakarta.persistence.*;
import org.hibernate.annotations.UuidGenerator;
import java.util.UUID;
@Entity
@Table(name = "orders")
public class Order {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME) // UUID v7
private UUID id;
private String status;
// getters / setters
}
With this annotation, Hibernate generates a UUID v7 before each INSERT — no @GeneratedValue needed. The resulting IDs sort chronologically, which keeps PostgreSQL B-tree indexes healthy.
java-uuid-generator (JUG) library
For UUID v7 outside of Hibernate or in non-JPA code, use the java-uuid-generator (JUG) library:
<!-- pom.xml -->
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>5.1.0</version>
</dependency>
import com.fasterxml.uuid.Generators;
import java.util.UUID;
// UUID v7 — time-based epoch generator
UUID id = Generators.timeBasedEpochGenerator().generate();
System.out.println(id); // "018f3c4e-7a21-7b3c-9d4e-5f6a7b8c9d0e"
// UUID v4 — random (standard library is simpler for this)
UUID idV4 = UUID.randomUUID();
The TimeBasedEpochGenerator in JUG 5.x produces RFC 9562-compliant UUID v7 values with a monotonic counter for within-millisecond ordering.
Spring Boot JPA — full entity example
import jakarta.persistence.*;
import org.hibernate.annotations.UuidGenerator;
import java.util.UUID;
@Entity
@Table(name = "products")
public class Product {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
@Column(name = "id", updatable = false, nullable = false)
private UUID id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private java.math.BigDecimal price;
// Default constructor required by JPA
protected Product() {}
public Product(String name, java.math.BigDecimal price) {
this.name = name;
this.price = price;
}
public UUID getId() { return id; }
public String getName() { return name; }
public java.math.BigDecimal getPrice() { return price; }
}
// Repository
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface ProductRepository extends JpaRepository<Product, UUID> {}
// Service
@Service
public class ProductService {
private final ProductRepository repo;
public ProductService(ProductRepository repo) { this.repo = repo; }
public Product create(String name, java.math.BigDecimal price) {
return repo.save(new Product(name, price));
}
public Optional<Product> findById(UUID id) {
return repo.findById(id);
}
}
Parsing and validating UUIDs
import java.util.UUID;
// Parse — throws IllegalArgumentException if invalid
public static UUID parseUUID(String s) {
return UUID.fromString(s);
}
// Safe parse — returns null on invalid input
public static UUID safeParseUUID(String s) {
try {
return UUID.fromString(s);
} catch (IllegalArgumentException e) {
return null;
}
}
// Validate without parsing
public static boolean isValidUUID(String s) {
if (s == null || s.length() != 36) return false;
try {
UUID.fromString(s);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
// Check version
UUID id = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
System.out.println(id.version()); // 4
UUID in PostgreSQL from Java
Use the uuid column type in PostgreSQL — never VARCHAR(36):
-- PostgreSQL schema
CREATE TABLE products (
id uuid PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) NOT NULL
);
With Spring Data JPA and the postgresql driver, UUID Java objects map directly to uuid PostgreSQL columns — no manual conversion needed. The driver handles the binary encoding.
// Spring Data JPA — UUID primary key maps automatically
@Column(columnDefinition = "uuid", updatable = false)
private UUID id;
For UUID v7 as a PostgreSQL column default (PostgreSQL 18+):
-- PostgreSQL 18+ — server generates UUID v7
ALTER TABLE products ALTER COLUMN id SET DEFAULT uuidv7();
See UUID in databases for the full PostgreSQL, MySQL, and SQL Server storage guide.
UUID string formats in Java
UUID id = UUID.randomUUID();
// Standard hyphenated form (36 chars) — RFC 9562 canonical
id.toString(); // "550e8400-e29b-41d4-a716-446655440000"
// No hyphens (32 chars)
id.toString().replace("-", ""); // "550e8400e29b41d4a716446655440000"
// Uppercase (not standard but sometimes required)
id.toString().toUpperCase(); // "550E8400-E29B-41D4-A716-446655440000"
// Most significant / least significant bits
id.getMostSignificantBits(); // first 64 bits as long
id.getLeastSignificantBits(); // last 64 bits as long
RFC 9562 specifies lowercase as the canonical form. UUID.fromString() accepts both cases. GeeksforGeeks has a compact reference for java.util.UUID methods including comparison, version reading, and string formatting.
Common mistakes
- Using
new UUID(0, 0)for a nil UUID. The nil UUID isUUID.fromString("00000000-0000-0000-0000-000000000000")— constructing it from longs is correct but less readable. - Comparing with
==instead of.equals(). UUID objects are value types — always useid.equals(otherId), neverid == otherId. - Using
UUID.randomUUID()for UUID v7.randomUUID()always produces v4. For v7, use Hibernate or JUG. - Storing as String in JPA. Map the field as
UUID, notString, so the driver uses binary storage in PostgreSQL.
Related guides
- UUID v4 vs UUID v7 — which version to use and why
- UUID in databases — PostgreSQL, MySQL storage
- UUID in Spring Boot — Hibernate, JPA entity patterns
- UUID v7 ORM support — state of all ORMs in 2026
External references
- github.com/f4b6a3/uuid-creator: UUID Creator — a comprehensive Java library for generating UUID v1–v8
- github.com/cowtowncoder/java-uuid-generator: JUG (Java UUID Generator) — widely used library powering Hibernate’s UUID v7 support
- Oracle Java 21 docs — java.util.UUID: official API reference for UUID.randomUUID(), fromString(), and getMostSignificantBits()
- GeeksforGeeks — java.util.UUID class: practical guide to UUID generation and manipulation in Java
- dev.to — UUID v7 in Java, Hibernate, JPA: community guide on Hibernate 6.5 @UuidGenerator with Spring Boot
- Medium — Generating UUIDs in Java: deep-dive covering java.util.UUID, JUG, Hibernate, and Spring Data JPA patterns
Frequently asked questions
How do I generate a UUID in Java?
Use java.util.UUID.randomUUID() for a random UUID v4 — it is in the standard library with no dependencies. For UUID v7, use Hibernate 6.5+ with @UuidGenerator(style = UuidGenerator.Style.TIME), or the java-uuid-generator (JUG) library via Generators.timeBasedEpochGenerator().generate().
Does Hibernate support UUID v7?
Yes. Hibernate 6.5+ generates UUID v7 via @UuidGenerator(style = UuidGenerator.Style.TIME) on a UUID id field. Spring Boot 3.2+ ships Hibernate 6.5+ and supports this annotation out of the box. For older Hibernate, use the java-uuid-generator (JUG) library.
Do UUIDs hurt database index performance?
UUID v4 does — its randomness causes every insert to land at a different leaf page, leading to page splits and poor cache locality. UUID v7 embeds a millisecond timestamp so consecutive inserts cluster together, behaving like an auto-increment integer for B-tree purposes.
How do I generate a UUID in Java?
Use java.util.UUID.randomUUID() for a random UUID v4 — it is in the standard library and requires no dependencies. For UUID v7, use Hibernate 6.5+ with @UuidGenerator(style = UuidGenerator.Style.TIME) or the java-uuid-generator (JUG) library.
Does Java support UUID v7?
Not in the standard library as of Java 21. For UUID v7 in Java, use Hibernate 6.5+ (which generates v7 via @UuidGenerator TIME style) or the java-uuid-generator library. Spring Boot 3.2+ with Hibernate 6.5+ supports UUID v7 entity IDs out of the box.
What is java.util.UUID?
java.util.UUID is Java's built-in UUID class in the standard library. UUID.randomUUID() generates a random UUID v4. UUID.fromString(s) parses a UUID string and throws IllegalArgumentException if invalid. The class has methods like toString(), getLeastSignificantBits(), and getMostSignificantBits().
How do I use UUID as a JPA entity ID in Spring Boot?
Annotate the id field with @Id and @GeneratedValue. For UUID v4, use @GeneratedValue(strategy = GenerationType.UUID) in Hibernate 6+. For UUID v7, use @UuidGenerator(style = UuidGenerator.Style.TIME) from Hibernate 6.5+. Store as UUID type in PostgreSQL for native 16-byte storage.
How do I parse and validate a UUID in Java?
Use UUID.fromString(s) — it throws IllegalArgumentException for any invalid UUID string. Wrap it in a try-catch for safe parsing. There is no isValid() method in the standard library; a regex or try-catch is the standard approach.
How do I generate a UUID in Java without a library?
Use UUID.randomUUID() from java.util.UUID — it is in the standard library (no import beyond java.util.UUID needed) and generates a cryptographically secure UUID v4. For UUID v7, a library is required since the standard library does not yet support it.