What is @Id Annotation in JPA?
@Id is a JPA annotation used to mark a field as the primary key of an entity class.
It uniquely identifies each record in a database table.
In simple words:
“@Id tells JPA which field acts as the unique identifier for the entity.”
What is a Primary Key?
A primary key is a column that uniquely identifies each row in a database table.
Example:
| ID | Name | |
|---|---|---|
| 1 | Naresh | naresh@gmail.com |
| 2 | Kumar | kumar@gmail.com |
Here:
ID
is the primary key because it uniquely identifies each student.
Why @Id Annotation is Needed
JPA and Hibernate require every entity to have a primary key.
Without @Id:
- Hibernate cannot uniquely identify records
- CRUD operations may fail
- Entity mapping becomes invalid
Basic @Id Example
@Entity
public class Student {
@Id
private Long id;
private String name;
private String email;
}
What Happens Internally?
Hibernate reads:
@Id
private Long id;
and treats:
id
as the primary key column in the database table.
Database Table Mapping Example
| Java Field | Database Column |
|---|---|
| id | PRIMARY KEY |
| name | name |
Generated SQL Example
CREATE TABLE student (
id BIGINT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
)
Can an Entity Exist Without @Id?
No.
Every JPA entity must contain a primary key field.
Otherwise Hibernate throws runtime exceptions.
Common Error Without @Id
No identifier specified for entity
Auto-Generated IDs
Usually IDs are generated automatically using:
@GeneratedValue
Example
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
What is @GeneratedValue?
It automatically generates primary key values.
Generation Strategies
| Strategy | Description |
|---|---|
| IDENTITY | Uses auto-increment column |
| SEQUENCE | Uses database sequence |
| TABLE | Uses table-based generator |
| AUTO | Automatically selects strategy |
IDENTITY Strategy Example
@GeneratedValue(
strategy = GenerationType.IDENTITY
)
Commonly used with MySQL auto-increment columns.
SEQUENCE Strategy Example
@GeneratedValue(
strategy = GenerationType.SEQUENCE
)
Commonly used with Oracle and PostgreSQL.
Composite Primary Keys
Some tables require multiple columns as primary keys.
JPA supports:
- @EmbeddedId
- @IdClass
Simple Composite Key Example
@Embeddable
public class StudentCourseId {
private Long studentId;
private Long courseId;
}
Entity with Composite Key
@Entity
public class StudentCourse {
@EmbeddedId
private StudentCourseId id;
}
Repository Example
public interface StudentRepository
extends JpaRepository<Student, Long> {
}
Save Entity Example
@Autowired
private StudentRepository repository;
public Student saveStudent() {
Student student = new Student();
student.setName("Naresh");
student.setEmail("naresh@gmail.com");
return repository.save(student);
}
Generated Insert Query
INSERT INTO student(name, email)
VALUES (?, ?)
Find By ID Example
public Optional<Student> getStudent(
Long id) {
return repository.findById(id);
}
Delete By ID Example
repository.deleteById(1L);
Entity Lifecycle and @Id
Hibernate uses the primary key to track entity lifecycle states.
Entity Lifecycle States
| State | Description |
|---|---|
| Transient | Object not saved yet |
| Persistent | Object managed by Hibernate |
| Detached | Object disconnected from session |
| Removed | Object marked for deletion |
Best Practices for @Id
- Always define a primary key
- Use Long or UUID for IDs
- Prefer auto-generated IDs
- Keep IDs immutable when possible
- Use meaningful naming conventions
Advantages of @Id Annotation
- Uniquely identifies records
- Enables CRUD operations
- Supports entity tracking
- Improves database integrity
- Required for JPA entity management
Disadvantages of Poor Primary Key Design
- Duplicate records
- Poor query performance
- Relationship issues
- Difficult maintenance
Real-Time Example in Banking Application
Banking system contains entities such as:
- Customer
- Account
- Transaction
Each entity uses:
@Id
to uniquely identify records.
Difference Between @Id and @GeneratedValue
| Feature | @Id | @GeneratedValue |
|---|---|---|
| Purpose | Marks primary key | Generates primary key value |
| Mandatory | Yes | No |
| Usage | Entity identification | Auto ID generation |
Common Interview Questions on @Id
What is @Id annotation?
@Id marks a field as the primary key of an entity.
Is @Id mandatory in JPA?
Yes, every entity must have a primary key.
What is the purpose of @GeneratedValue?
It automatically generates primary key values.
Can we use String as primary key?
Yes, but Long and UUID are more commonly recommended.
What happens if @Id is missing?
Hibernate throws runtime exceptions because the entity has no identifier.
Conclusion
The @Id annotation is one of the most important annotations
in JPA and Hibernate.
It uniquely identifies each entity object and acts as the primary key in the database.
@Id enables:
- CRUD operations
- Entity tracking
- Relationship mapping
- Database integrity
Understanding @Id is essential for Spring Boot developers
because every enterprise application relies heavily
on properly designed primary keys and entity management.