How do you configure a JPA entity to automatically generate its primary key value?

How do you configure a JPA entity to automatically generate its primary key value?

A) By using the @Id and @GeneratedValue annotations
B) By using the @PrimaryKey and @AutoGenerate annotations
C) By using the @Table and @GeneratedKey annotations
D) By using the @PrimaryKey and @Sequence annotations

Answer:

A) By using the @Id and @GeneratedValue annotations

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.

Reference links:

Spring Data JPA Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top