Blog
Wild & Free Tools

How to Generate UUID in Java

Last updated: March 2026 6 min read
Quick Answer

Table of Contents

  1. Basic UUID Generation
  2. UUID Without Dashes in Java
  3. Parse and Validate UUID Strings
  4. UUID in JPA / Hibernate
  5. UUID in Spring Boot
  6. UUID Performance in Java
  7. Frequently Asked Questions

Java has had built-in UUID support since Java 1.5. java.util.UUID is in the standard library — no Maven dependency, no import beyond the class itself. This guide covers generation, string conversion, database storage, validation, and Spring Boot integration.

Generate a UUID in Java — The Basic Method

One line of code, no dependencies:

import java.util.UUID;

UUID id = UUID.randomUUID();
System.out.println(id);
// Output: 550e8400-e29b-41d4-a716-446655440000

// As a String directly:
String uuid = UUID.randomUUID().toString();
System.out.println(uuid);
// "550e8400-e29b-41d4-a716-446655440000"

UUID.randomUUID() uses SecureRandom internally — it is cryptographically secure and safe for database keys, session IDs, and any context requiring unpredictable identifiers.

UUID Without Dashes in Java

Remove hyphens using replace() or the "N"-equivalent pattern:

// Remove hyphens from UUID string:
String noDashes = UUID.randomUUID().toString().replace("-", "");
// "550e8400e29b41d4a716446655440000"

// Uppercase variant:
String upper = UUID.randomUUID().toString().replace("-", "").toUpperCase();
// "550E8400E29B41D4A716446655440000"

Java does not have a format specifier equivalent to C#'s "N"replace() is the idiomatic approach.

Parse and Validate UUID Strings in Java

UUID.fromString(String) parses a UUID string back into a UUID object. It throws IllegalArgumentException if the format is invalid:

// Parse a UUID string:
UUID parsed = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
System.out.println(parsed.version()); // 4
System.out.println(parsed.variant()); // 2

// Validate without exception:
public static boolean isValidUUID(String str) {
    try {
        UUID.fromString(str);
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    }
}

System.out.println(isValidUUID("550e8400-e29b-41d4-a716-446655440000")); // true
System.out.println(isValidUUID("not-a-uuid")); // false

Note: UUID.fromString() accepts any UUID version — if you need to specifically validate v4, check parsed.version() == 4 after parsing.

Sell Custom Apparel — We Handle Printing & Free Shipping

UUID in JPA and Hibernate

JPA and Hibernate have native UUID support. The recommended approach for JPA 3.1+ (Jakarta Persistence):

import jakarta.persistence.*;
import java.util.UUID;

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    private String status;

    // getters and setters
}

For older JPA / Hibernate 5 with manual generation:

@Entity
public class Order {

    @Id
    @Column(columnDefinition = "uuid", updatable = false, nullable = false)
    private UUID id = UUID.randomUUID();

    private String status;
}

PostgreSQL stores UUID type natively as 16 bytes. MySQL does not have a UUID column type — use CHAR(36) or BINARY(16) and handle conversion in the entity:

// MySQL with BINARY(16) storage:
@Column(name = "id", columnDefinition = "BINARY(16)")
private UUID id;

UUID in Spring Boot — Path Variables and Request Bodies

Spring MVC handles UUID path variables natively — the framework converts the String to a UUID object automatically:

@RestController
@RequestMapping("/orders")
public class OrderController {

    @GetMapping("/{id}")
    public ResponseEntity<Order> getOrder(@PathVariable UUID id) {
        // Spring converts the path string to UUID automatically
        // Returns 400 Bad Request if the format is invalid
        return ResponseEntity.ok(orderService.findById(id));
    }

    @PostMapping
    public ResponseEntity<Order> createOrder(@RequestBody CreateOrderRequest req) {
        UUID orderId = UUID.randomUUID();
        // use orderId as the new entity's ID
        return ResponseEntity.ok(orderService.create(orderId, req));
    }
}

Spring Boot automatically returns a 400 Bad Request if a path variable UUID is malformed — you do not need manual validation in the controller.

For JSON serialization, UUID serializes as a plain string by default with Jackson — no custom serializer needed.

UUID Performance Notes

UUID.randomUUID() uses SecureRandom, which is thread-safe but can be a bottleneck at very high generation rates (millions/second) due to entropy pool contention.

For high-throughput scenarios:

// Option 1: Use ThreadLocalRandom for non-security-critical IDs (faster, less random):
// Not recommended for security contexts

// Option 2: Pre-generate UUIDs in bulk (rare need):
List<UUID> batch = IntStream.range(0, 1000)
    .mapToObj(i -> UUID.randomUUID())
    .collect(Collectors.toList());

// Option 3: Use UUID v7 via a library for sortable IDs:
// https://github.com/f4b6a3/uuid-creator
// UuidCreator.getTimeOrderedEpoch() // UUID v7

For typical web applications generating UUIDs per-request, UUID.randomUUID() is fast enough — contention only matters at extreme throughput.

Need a UUID Right Now?

The Cheetah UUID Generator produces RFC-compliant UUID v4 values instantly in your browser — paste them straight into your Java code, database seed, or test fixture.

Open Free UUID Generator

Frequently Asked Questions

Does Java need an external library to generate UUID?

No. java.util.UUID is part of the Java standard library since Java 1.5. UUID.randomUUID() generates a cryptographically secure UUID v4 with no dependencies.

How do I generate a UUID as a String in Java?

UUID.randomUUID().toString() returns the UUID in standard 36-character hyphenated format. Use .toString().replace("-", "") for the 32-character no-dashes format.

What is the difference between UUID.randomUUID() and new UUID()?

UUID.randomUUID() generates a random UUID v4 automatically. new UUID(long mostSigBits, long leastSigBits) constructs a UUID from two 64-bit values you provide — used when reconstructing a UUID from known bit values, not for random generation.

How do I store UUID as a primary key in Spring Boot with MySQL?

MySQL has no native UUID type. Use @Column(columnDefinition = "CHAR(36)") for human-readable storage, or BINARY(16) with a byte array converter for compact storage. PostgreSQL supports a native UUID column type and is the preferred database for UUID-keyed tables.

How do I compare two UUID objects in Java?

Use uuid1.equals(uuid2) — do not use == for object comparison. UUID.compareTo() provides lexicographic ordering. If comparing a UUID to a String, parse the String first: UUID.fromString(str).equals(uuid).

Ryan Callahan
Ryan Callahan Lead Software Engineer

Ryan architected the client-side processing engine that powers every tool on WildandFree — ensuring your files never leave your browser.

More articles by Ryan →
Launch Your Own Clothing Brand — No Inventory, No Risk