0
0
SpringbootConceptBeginner · 3 min read

@Id Annotation in Spring Boot: What It Is and How It Works

In Spring Boot, the @Id annotation marks a field in an entity class as the primary key, which uniquely identifies each record in the database. It tells Spring Data JPA which property to use as the unique identifier for database operations.
⚙️

How It Works

The @Id annotation works like a name tag for each record in a database table. Imagine a classroom where every student wears a unique ID badge so the teacher can quickly find or recognize them. Similarly, in a database, each row needs a unique identifier to distinguish it from others.

When you use @Id in a Spring Boot entity, you tell the system which field acts as this unique badge. This helps Spring Data JPA perform actions like finding, updating, or deleting records efficiently because it knows exactly which record to target.

💻

Example

This example shows a simple entity class with the @Id annotation marking the primary key field.

java
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    private String name;

    public User() {}

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
🎯

When to Use

Use @Id whenever you create an entity class that maps to a database table in Spring Boot. It is essential for defining the primary key, which is required for database operations like saving, updating, and deleting records.

For example, in an online store application, you would use @Id on the product ID field to uniquely identify each product. Without it, the system wouldn't know how to distinguish one product from another.

Key Points

  • @Id marks the primary key field in an entity.
  • It uniquely identifies each record in the database.
  • Required for Spring Data JPA to perform CRUD operations.
  • Works together with @Entity to map Java classes to database tables.

Key Takeaways

@Id defines the unique identifier for database records in Spring Boot entities.
It is essential for Spring Data JPA to manage data correctly.
Always use @Id on a field in your entity class to mark the primary key.
Without @Id, Spring Boot cannot perform database operations on the entity.