Spring Boot UUID: JPA Entity, REST Controller, and Repository
- Use @GeneratedValue(strategy = GenerationType.UUID) on a UUID id field in Spring Boot 3+.
- Hibernate maps UUID to a native UUID column in PostgreSQL and a BINARY(16) in MySQL.
- REST controllers accept UUIDs as @PathVariable — Spring auto-validates the format.
- For Spring Boot 2.x, use @GenericGenerator with the "uuid2" strategy instead.
Table of Contents
Spring Boot 3+ (Hibernate 6) has first-class UUID support — no extra annotations or custom generators needed. Declare a UUID field, add @GeneratedValue(strategy = GenerationType.UUID), and Hibernate handles storage, index mapping, and generation. This guide covers the full setup: entity definition, repository, REST controller, and older Spring Boot 2.x compatibility.
Defining the JPA Entity with UUID Primary Key
Spring Boot 3+ with Hibernate 6:
import jakarta.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private String customerEmail;
private java.math.BigDecimal total;
// getters and setters
public UUID getId() { return id; }
public void setId(UUID id) { this.id = id; }
public String getCustomerEmail() { return customerEmail; }
public void setCustomerEmail(String email) { this.customerEmail = email; }
public java.math.BigDecimal getTotal() { return total; }
public void setTotal(java.math.BigDecimal total) { this.total = total; }
}
The GenerationType.UUID strategy tells Hibernate to generate a random UUID v4 value before the INSERT. The application receives the UUID immediately — no round-trip to the database needed to learn the new ID.
Spring Boot 2.x Compatibility: @GenericGenerator
If you're on Spring Boot 2.x (Hibernate 5), GenerationType.UUID doesn't exist. Use:
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.UUID;
@Entity
public class Order {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(updatable = false, nullable = false)
private UUID id;
}
The "uuid2" strategy generates standard UUID v4 values. The older "uuid" strategy generates a non-standard hex format — avoid it.
Spring Data JPA Repository
The repository is straightforward — just use UUID as the ID type:
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface OrderRepository extends JpaRepository<Order, UUID> {
// Spring Data generates findById(UUID id), save(), deleteById() etc.
}
All the standard JPA methods accept UUID directly. No special handling required.
REST Controller: UUID Path Variables and Response
Spring MVC converts @PathVariable UUID id from the URL string automatically — and returns a 400 Bad Request if the string isn't a valid UUID format:
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderRepository orderRepository;
public OrderController(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@GetMapping("/{id}")
public Order getOrder(@PathVariable UUID id) {
return orderRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND, "Order not found"
));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Order createOrder(@RequestBody Order order) {
return orderRepository.save(order);
// response body includes the generated UUID id
}
}
The JSON response serializes UUID as a hyphenated string ("id": "550e8400-e29b-41d4-a716-446655440000") via Jackson's default UUID serializer. No additional configuration needed.
UUID Storage by Database: PostgreSQL vs MySQL
Hibernate 6 maps UUID fields differently depending on the database dialect:
- PostgreSQL — native
UUIDcolumn type (16 bytes). Hibernate usesPostgreSQLUUIDJdbcTypeautomatically when the PostgreSQL dialect is detected. - MySQL / MariaDB — stores as
BINARY(16)by default in Hibernate 6 (more efficient thanVARCHAR(36)). If you need human-readable storage, add@JdbcTypeCode(SqlTypes.VARCHAR)to the field. - H2 (testing) — stored as
UUIDtype, fully compatible with both dialects above.
Use the free UUID generator above to create test UUIDs for Postman collections, integration tests, or Spring Boot test fixtures.
Generate Test UUIDs for Spring Boot Integration Tests
The Cheetah UUID Generator creates RFC-compliant UUID v4 strings — paste them directly into Postman, Spring Boot test fixtures, or your application.properties seed data.
Open Free UUID GeneratorFrequently Asked Questions
Does Spring Boot auto-generate the UUID before or after insert?
Before insert. Hibernate generates the UUID in Java and includes it in the INSERT statement. The entity has its ID populated immediately after save(), without a database round-trip.
How do I return the UUID in camelCase in the JSON response?
Jackson serializes UUID fields using the field name as-is. If your field is named "id", the JSON key is "id". No extra configuration needed.
Can I use String instead of UUID as the field type?
Yes, but not recommended. Storing as UUID type in Java gives you type safety, proper Hibernate mapping, and avoids format bugs. Use String only if you have a specific interop reason.
What happens if a client sends a malformed UUID in the URL?
Spring MVC returns a 400 Bad Request automatically — the @PathVariable UUID conversion fails before your controller method runs.

