what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why t...
Categories:
Understanding @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) in JPA/Hibernate

Explore the crucial role of @Id and @GeneratedValue with GenerationType.IDENTITY in Java Persistence API (JPA) and Hibernate for managing primary keys in database entities.
When working with Java applications that interact with relational databases, especially using frameworks like JPA and Hibernate, managing primary keys is a fundamental task. The @Id
and @GeneratedValue
annotations are central to this process, providing a declarative way to define how an entity's primary key is identified and generated. This article delves into the purpose of these annotations, with a specific focus on GenerationType.IDENTITY
, explaining why it's a common and often preferred strategy for primary key generation.
The Role of @Id: Marking the Primary Key
The @Id
annotation is a core component of the Java Persistence API (JPA). Its primary purpose is to designate a field in an entity class as the primary key of the corresponding database table. Every JPA entity must have a primary key, and this annotation fulfills that requirement. The primary key uniquely identifies each record in the table, ensuring data integrity and enabling efficient data retrieval and manipulation.
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
public class Product {
@Id
private Long id;
private String name;
private double price;
// Getters and Setters
}
Basic JPA Entity with @Id annotation
@GeneratedValue: Automating Primary Key Generation
While @Id
marks a field as the primary key, @GeneratedValue
specifies how the value for that primary key is actually generated. Databases often handle primary key generation automatically to ensure uniqueness and sequential ordering. The strategy
attribute within @GeneratedValue
allows you to choose from several approaches for this generation. These strategies are defined by the GenerationType
enum:
AUTO
: Lets the persistence provider (e.g., Hibernate) choose the generation strategy based on the database dialect.IDENTITY
: Relies on an identity column in the database, where the database itself assigns a unique, auto-incrementing value upon insertion.SEQUENCE
: Uses a database sequence to generate primary key values.TABLE
: Uses a separate database table to simulate a sequence for primary key generation.
flowchart TD A[Entity Creation] --> B{Is @Id present?} B -- Yes --> C{Is @GeneratedValue present?} C -- Yes --> D{Which GenerationType?} D -- IDENTITY --> E[Database Auto-Increment] D -- SEQUENCE --> F[Database Sequence] D -- TABLE --> G[Separate Table Sequence] D -- AUTO --> H[Provider Chooses] C -- No --> I[Manual ID Assignment] B -- No --> J[Error: No Primary Key]
Primary Key Generation Flow in JPA
Understanding GenerationType.IDENTITY
The GenerationType.IDENTITY
strategy is one of the most commonly used options for primary key generation. When you specify GenerationType.IDENTITY
, you are instructing JPA (and by extension, Hibernate) to rely on the database's auto-incrementing column feature. This means that the database itself is responsible for generating a unique, sequential value for the primary key every time a new record is inserted into the table.
Why 'IDENTITY'?
The term 'IDENTITY' refers to the identity column property in SQL databases (e.g., AUTO_INCREMENT
in MySQL, IDENTITY
in SQL Server, SERIAL
in PostgreSQL). This property ensures that the database automatically assigns a unique, incrementing value to the column for each new row. This approach simplifies application development because the application doesn't need to manage primary key values; it simply inserts a new record, and the database handles the rest.
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 username;
private String email;
// Getters and Setters
}
JPA Entity with @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)
GenerationType.IDENTITY
, the primary key value is only available after the entity has been persisted (i.e., after the INSERT
statement has been executed by the database). This is because the database generates the ID, not the application.Advantages and Considerations of GenerationType.IDENTITY
Advantages:
- Simplicity: It's straightforward to use and requires minimal configuration in your application code.
- Database-managed uniqueness: The database guarantees unique primary keys, reducing the chance of application-level errors.
- Performance: For single-threaded inserts, it can be very efficient as the database handles the ID generation directly.
Considerations:
- ID availability: As mentioned, the ID is not available until after the
INSERT
operation. This can be a limitation if you need the ID for related operations before the entity is fully persisted. - Batch inserts:
GenerationType.IDENTITY
can sometimes hinder the performance of batch inserts. Since each insert operation needs to be executed individually to retrieve the generated ID, it prevents Hibernate from optimizing multiple inserts into a single batch statement. - Database portability: While most modern relational databases support identity columns, the exact syntax and behavior might vary slightly, though JPA abstracts most of this away.

How GenerationType.IDENTITY
works: Application sends data, database generates ID, then returns the ID.
In summary, @Id
is essential for marking the primary key, and @GeneratedValue(strategy = GenerationType.IDENTITY)
is a powerful and common choice for letting the database handle the automatic generation of these unique identifiers. It simplifies development by delegating ID management to the database, making it a popular choice for many applications, especially where batching inserts is not a critical performance concern.