Java – how to specify multiple fields as the primary key of an entity (using JPA)
See English answers > JPA composite primary key 2
Suppose we have a personnel table of SSN, nationality and name An SSN is defined as a number that identifies a person in its country Therefore, we may have two people of the same number in two different countries The primary key of this table can be SSN nationality Is there any way to map these two fields to objects using JPA? Or it is the only way to create an automatically generated ID and annotate it with @ ID
CREATE TABLE PERSON ( SSN INT,NATIONALITY VARCHAR,NAME VARCHAR )
Solution
Yes, it is possible A composite primary key consists of multiple primary key fields Each primary key field must be one of the fields supported by JPA type
@Entity @IdClass(PersonId.class) public class Person { @Id int ssn; @Id String nationality; .... }
For entities with multiple keys, JPA needs to define special ID classes This class should be attached to the entity class using the @ IdClass annotation
class PersonId { int ssn; String nationality; }
The ID class reflects the primary key field, and its object can represent the primary key value