Clean • Professional
In JPA, the @GeneratedValue annotation is used alongside @Id to automatically generate primary key values for entities. Choosing the right ID generation strategy is crucial for database consistency, performance, and scalability in Spring Data JPA and Hibernate applications.
JPA provider automatically chooses the most suitable strategy based on the database (could be IDENTITY, SEQUENCE, or TABLE).
Usage:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
Key Points:
Use Case:
Portable applications where you don’t want to worry about database-specific ID generation.
Uses the database’s auto-increment feature to generate IDs.
Usage:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Key Points:
Use Case:
Applications using MySQL or other databases with auto-increment columns.
Uses a database sequence object to generate unique IDs.
Usage:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
Key Points:
@SequenceGenerator.Example with Custom Sequence:
@Id
@SequenceGenerator(name="user_seq", sequenceName="user_sequence", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="user_seq")
private Long id;
Use Case:
Applications needing high-performance inserts with sequence-supporting databases.
Uses a separate table to maintain and generate unique IDs.
Usage:
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
Key Points:
IDENTITY or SEQUENCE for high-volume applications.Use Case:
Legacy databases or situations where sequence/identity is not available.
| Strategy | How It Works | Database Support | Pros | Cons |
|---|---|---|---|---|
| AUTO | JPA automatically selects a strategy based on the database | All databases | Easy to use, portable across databases | Behavior may vary depending on the DB |
| IDENTITY | Uses the database’s auto-increment feature | MySQL, SQL Server | Simple, widely supported | Inefficient for batch inserts |
| SEQUENCE | Uses a database sequence object to generate IDs | Oracle, PostgreSQL | Efficient, supports batch inserts | Requires database sequence support |
| TABLE | Maintains a separate table to generate IDs | Any database | Works on any DB, database-independent | Slower performance due to extra table lookup |
JPA ID generation strategies allow automatic handling of primary keys in a flexible and database-aware manner. Choosing the right strategy ensures efficient, scalable, and maintainable Spring Data JPA applications.
AUTO – Simple, portable.IDENTITY – Easy, auto-increment.SEQUENCE – Efficient for sequence-based databases.TABLE – Database-independent, less efficient.Using these strategies properly eliminates manual key management and simplifies ORM-based development with Hibernate and Spring Data JPA.