@GeneratedValue Annotation in Spring Boot: What It Is and How It Works
@GeneratedValue annotation in Spring Boot is used to automatically generate unique primary key values for entity objects when saving them to the database. It works with @Id to tell Spring Data JPA how to create these keys, simplifying database record creation.How It Works
Imagine you have a list of items and each item needs a unique number to identify it, like a ticket number. The @GeneratedValue annotation acts like a ticket machine that hands out these unique numbers automatically whenever you add a new item.
In Spring Boot, when you mark a field with @Id and @GeneratedValue, the framework takes care of creating a unique value for that field each time you save a new entity. This means you don't have to manually assign IDs, which helps avoid mistakes like duplicate keys.
The annotation supports different strategies for generating these values, such as incrementing numbers or using database sequences, depending on what fits your database setup best.
Example
This example shows a simple entity class where the id field is automatically generated when a new user is saved.
import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; public User() {} public User(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
When to Use
Use @GeneratedValue whenever you want your database to handle creating unique IDs for your entities automatically. This is especially useful in applications where you add many records and need to ensure each one has a unique identifier without extra coding.
For example, in a user management system, product catalog, or order tracking app, letting the database generate IDs reduces errors and simplifies your code.
Key Points
- @GeneratedValue works with
@Idto auto-generate primary keys. - Supports different strategies like
IDENTITY,SEQUENCE, andAUTO. - Helps avoid manual ID assignment and duplicate keys.
- Commonly used in Spring Data JPA entity classes.
Key Takeaways
@GeneratedValue automatically creates unique IDs for entity primary keys.@Id in Spring Data JPA entity classes.