In Spring Boot (and more broadly in Java Persistence API (JPA) applications), the @Id annotation is used to mark a field as the primary key of an entity. To automatically generate the value for this primary key, you can use the @GeneratedValue annotation in conjunction with @Id.
Here’s a brief overview of how these annotations are
used:
@Id
Annotation
- Purpose:
Specifies the primary key of an entity.
- Usage:
Applied to the field that should act as the primary key of the entity.
@GeneratedValue
Annotation
- Purpose: Specifies the strategy for
generating the primary key values.
- Usage: Applied to the same field as
@Id
to define how the primary key values should be generated.
@Entity
public
class User {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY) // or other strategy
private Long id;
// other fields, getters, setters
}
Generation Strategies
The @GeneratedValue
annotation
supports several strategies:
1. GenerationType.AUTO
:
The persistence provider will choose the appropriate strategy for the database.
This is the default if no strategy is specified.
@GeneratedValue(strategy = GenerationType.AUTO)
2. GenerationType.IDENTITY
:
Uses an auto-incrementing column in the database. This is often used with
databases like MySQL.
@GeneratedValue(strategy = GenerationType.IDENTITY)
3. GenerationType.SEQUENCE
:
Uses a database sequence to generate unique values. This is commonly used with
databases like Oracle.
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_sequence", allocationSize = 1)
No comments:
Post a Comment