0
0
Spring Bootframework~3 mins

Why @Id and @GeneratedValue for primary keys in Spring Boot? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could handle unique IDs all by itself, so you never worry about duplicates again?

The Scenario

Imagine you are building a simple app to store user data. You try to assign unique IDs to each user manually by typing numbers yourself every time you add a new user.

The Problem

Manually assigning IDs is slow and risky. You might accidentally reuse an ID, causing data mix-ups or errors. It's like trying to keep track of library books by writing numbers on paper without a system--easy to lose track and make mistakes.

The Solution

Using @Id and @GeneratedValue in Spring Boot tells the system to automatically create unique IDs for each record. This removes the hassle and errors of manual ID assignment, making your app more reliable and easier to build.

Before vs After
Before
user.setId(1);
userRepository.save(user);
After
@Id
@GeneratedValue
private Long id;

userRepository.save(user);
What It Enables

This lets your app safely and automatically handle unique identifiers, so you can focus on building features instead of managing IDs.

Real Life Example

Think of a ticketing system where each ticket needs a unique number. Using @GeneratedValue is like having a machine that prints the next ticket number automatically, so no two tickets share the same number.

Key Takeaways

@Id marks the primary key field in your data model.

@GeneratedValue tells Spring Boot to auto-create unique IDs.

This avoids manual errors and simplifies data management.