SoFunction
Updated on 2025-05-11

Detailed explanation of the use of @Id and @GeneratedValue for Java primary key generation

introduction

Database operations are an indispensable part of Java enterprise-level development. In the database table, the primary key is the important field that uniquely identifies each record. When using JPA (Java Persistence API) for object-relational mapping, you need to specify a primary key for the entity class and determine the primary key generation strategy.@Idand@GeneratedValueAnnotations are key annotations in JPA that define primary key and primary key generation strategies. Understanding the use of these two annotations and different primary key generation strategies is crucial to developing efficient and stable data persistence applications.

1. The function of @Id annotation

@IdAnnotation is annotation in JPA that identifies the attributes of an entity class as primary key. In the JPA entity class, there must be an attribute@IdAnnotation tags to specify the primary key column in the database table that corresponds to this property. The primary key is unique in the database and is used to uniquely identify each record in the table. Here is a simple example:

import ;
import ;
@Entity
public class Employee {
    @Id
    private Long id;
    private String name;
    private String department;
    public Employee() {
    }
    public Employee(Long id, String name, String department) {
         = id;
         = name;
         = department;
    }
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
         = department;
    }
}

In this example,idAttributes are@IdThe annotation mark is the primary key.

2. Overview of @GeneratedValue annotation

@GeneratedValueAnnotations are used to specify the generation strategy for primary keys. When using@IdAfter the annotation marks the primary key attribute, it can be used@GeneratedValueAnnotation to define how the value of the primary key is generated.@GeneratedValueAnnotations have two important attributes:strategyandgeneratorstrategyAttributes are used to specify primary key generation policy.generatorProperties are used to specify a custom primary key generator.

3. Different primary key generation strategies

1.

yes@GeneratedValueThe default policy for annotation. JPA will automatically select the appropriate primary key generation strategy based on the characteristics of the underlying database. For example, for databases that support autoincrement primary keys (such as MySQL), JPA may choose a self-increment policy; for databases that do not support autoincrement primary keys, another policy may be selected. Examples are as follows:

import ;
import ;
import ;
import ;
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = )
    private Long id;
    private String name;
    private double price;
    public Product() {
    }
    public Product(String name, double price) {
         = name;
         = price;
    }
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
         = price;
    }
}

In this example,idThe primary key generation strategy for attributes isAUTO

2.

The policy is suitable for databases that support auto-increment primary keys, such as MySQL, SQL Server, etc. When using this policy, the database automatically generates a unique autoincrement primary key value for newly inserted records. Examples are as follows:

import ;
import ;
import ;
import ;
@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = )
    private Long id;
    private String name;
    private String email;
    public Customer() {
    }
    public Customer(String name, String email) {
         = name;
         = email;
    }
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
         = email;
    }
}

In this example,idThe primary key generation strategy for attributes isIDENTITY, the database will be automatically inserted for the newly insertedCustomerRecord generation self-increasedidvalue.

3.

The policy is suitable for databases that support sequences, such as Oracle, PostgreSQL, etc. A sequence is an object used in the database to generate a unique number. When using this policy, you need to create the corresponding sequence in the database and@GeneratedValueThe name of the sequence specified in the annotation. Examples are as follows:

import ;
import ;
import ;
import ;
import ;
@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = , generator = "order_seq")
    @SequenceGenerator(name = "order_seq", sequenceName = "ORDER_SEQ", allocationSize = 1)
    private Long id;
    private String orderNumber;
    private double totalAmount;
    public Order() {
    }
    public Order(String orderNumber, double totalAmount) {
         = orderNumber;
         = totalAmount;
    }
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getOrderNumber() {
        return orderNumber;
    }
    public void setOrderNumber(String orderNumber) {
         = orderNumber;
    }
    public double getTotalAmount() {
        return totalAmount;
    }
    public void setTotalAmount(double totalAmount) {
         = totalAmount;
    }
}

In this example,@SequenceGeneratorAnnotation defines a name calledorder_seqsequence generator,sequenceNameSpecifies the name of the sequence in the database.allocationSizeSpecifies the number of numbers taken from the sequence each time.

4.

The policy uses a database table to simulate the functionality of a sequence to generate a unique primary key value. This strategy is suitable for databases that do not support sequences, or requires the consistency of primary key generation between multiple databases. Examples are as follows:

import ;
import ;
import ;
import ;
import ;
@Entity
public class Supplier {
    @Id
    @GeneratedValue(strategy = , generator = "supplier_gen")
    @TableGenerator(name = "supplier_gen", table = "ID_GENERATOR_TABLE", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE", pkColumnValue = "SUPPLIER_PK", allocationSize = 1)
    private Long id;
    private String name;
    private String contactInfo;
    public Supplier() {
    }
    public Supplier(String name, String contactInfo) {
         = name;
         = contactInfo;
    }
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public String getContactInfo() {
        return contactInfo;
    }
    public void setContactInfo(String contactInfo) {
         = contactInfo;
    }
}

In this example,@TableGeneratorAnnotation defines a name calledsupplier_gentable generator,tableSpecifies the table name used to generate the primary key.pkColumnNameandvalueColumnNameThe names of the primary key column and the value column are specified respectively.pkColumnValueSpecifies the primary key value corresponding to this entity class.

Summarize

@Idand@GeneratedValueAnnotations are important annotations in JPA for defining primary key and primary key generation strategies.@IdAnnotation is used to identify the attribute of the entity class as the primary key, and@GeneratedValueAnnotations are used to specify the primary key generation strategy. JPA provides a variety of primary key generation strategies, includingAUTOIDENTITYSEQUENCEandTABLE, Each strategy has its applicable scenarios and database types. Developers need to select appropriate primary key generation strategies based on specific database and business needs to ensure data integrity and consistency while improving development efficiency.

The above is the detailed explanation of the use of @Id and @GeneratedValue generated by Java primary key. For more information about Java @Id and @GeneratedValue, please follow my other related articles!