How do you configure a JPA entity to automatically generate its primary key value?
Answer:
Explanation:
In JPA, you can configure an entity to automatically generate its primary key value by using the @Id
and @GeneratedValue
annotations. The @Id
annotation defines the primary key, and the @GeneratedValue
annotation specifies that the primary key value should be automatically generated by the persistence provider.
For example:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and setters
}
In this example, the id
field is the primary key of the Product
entity. The @GeneratedValue(strategy = GenerationType.IDENTITY)
annotation specifies that the value of the id
field should be generated automatically, typically using an auto-increment strategy in the database.
Using the @Id
and @GeneratedValue
annotations simplifies the process of managing primary key values in JPA, ensuring that each entity instance has a unique identifier.