Java MCQ: Which annotation is used to automatically generate primary key values in JPA?
a) @AutoKey
b) @Id
c) @GeneratedValue
d) @KeyGenerator
Answer:
c) @GeneratedValue
Explanation:
The @GeneratedValue
annotation is used in JPA to automatically generate primary key values. This annotation is applied to the primary key field of an entity and allows the database or JPA provider to generate a unique identifier for each new entity instance.
Here’s an example:
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters and setters
}
In this example, the id
field is annotated with both @Id
and @GeneratedValue
, indicating that it is the primary key and its value will be automatically generated by the database using the IDENTITY
strategy.
Using @GeneratedValue
simplifies the process of assigning primary key values and ensures uniqueness for each entity instance.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html