How do you define a primary key in a JPA entity class?
A) By using the @Id annotation
B) By using the @PrimaryKey annotation
C) By using the @Column annotation
D) By using the @Table annotation
Answer:
A) By using the @Id annotation
Explanation:
The @Id
annotation in Spring Data JPA is used to define the primary key of an entity class. The primary key is a unique identifier for each entity instance, and it maps to the primary key column in the database table.
For example:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
}
In this example, the id
field is annotated with @Id
, indicating that it is the primary key of the User
entity. The @GeneratedValue
annotation specifies that the value of the primary key will be automatically generated, typically using an auto-increment strategy in the database.
The @Id
annotation is essential in JPA for establishing the entity’s identity, ensuring that each instance is uniquely identifiable within the database.