Jakarta Persistence / Spring Data JPA

@Id

Declare the entity primary key mapping. Boot 4.0.10 companion project; source-reviewed, not executed.

Formal Syntax & Structure

java syntaxjava
@Id

Working Example

Example Snippetjava
package example.catalog;import jakarta.persistence.*;import java.util.Objects;@Entity@Table(name="product")public class Product {    @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id;    @Column(nullable=false, unique=true, length=12) private String sku;    @Column(nullable=false) private int stock;    @Version @Column(nullable=false) private long version;    @ManyToOne(fetch=FetchType.LAZY, optional=false)    @JoinColumn(name="category_id", nullable=false) private Category category;    protected Product() {}    Product(String sku, int stock, Category category) {        if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || stock < 0)            throw new IllegalArgumentException("Invalid product");        this.sku = sku; this.stock = stock; this.category = Objects.requireNonNull(category);    }    public Long getId() { return id; }    public String getSku() { return sku; }    public int getStock() { return stock; }    public long getVersion() { return version; }    public Category getCategory() { return category; }    public void reserve(int amount) {        if (amount <= 0 || amount > stock) throw new IllegalArgumentException("Invalid reservation");        stock -= amount;    }}
Java Reference