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.@Id
and@GeneratedValue
Annotations 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
@Id
Annotation 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@Id
Annotation 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,id
Attributes are@Id
The annotation mark is the primary key.
2. Overview of @GeneratedValue annotation
@GeneratedValue
Annotations are used to specify the generation strategy for primary keys. When using@Id
After the annotation marks the primary key attribute, it can be used@GeneratedValue
Annotation to define how the value of the primary key is generated.@GeneratedValue
Annotations have two important attributes:strategy
andgenerator
。strategy
Attributes are used to specify primary key generation policy.generator
Properties are used to specify a custom primary key generator.
3. Different primary key generation strategies
1.
yes
@GeneratedValue
The 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,id
The 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,id
The primary key generation strategy for attributes isIDENTITY
, the database will be automatically inserted for the newly insertedCustomer
Record generation self-increasedid
value.
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
@GeneratedValue
The 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,@SequenceGenerator
Annotation defines a name calledorder_seq
sequence generator,sequenceName
Specifies the name of the sequence in the database.allocationSize
Specifies 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,@TableGenerator
Annotation defines a name calledsupplier_gen
table generator,table
Specifies the table name used to generate the primary key.pkColumnName
andvalueColumnName
The names of the primary key column and the value column are specified respectively.pkColumnValue
Specifies the primary key value corresponding to this entity class.
Summarize
@Id
and@GeneratedValue
Annotations are important annotations in JPA for defining primary key and primary key generation strategies.@Id
Annotation is used to identify the attribute of the entity class as the primary key, and@GeneratedValue
Annotations are used to specify the primary key generation strategy. JPA provides a variety of primary key generation strategies, includingAUTO
、IDENTITY
、SEQUENCE
andTABLE
, 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!