How to assign multiple fields as the primary key of an object (using JPA)

You can assign a primary key to your class using the @Id annotation in JPA. My question is if you do not want to have an automatically generated key in your tables and use fields (possibly more than one) as your primary key.

Say we have a table of people with SSN, NATIONALITY and NAME. SSN is defined as the number that a person identifies in his country. Thus, we can have two people with the same number in two different countries. The primary key for this table may be SSN + NATIONALITY. Is there a way to map these two fields using JPA and map it to an object? or the only way to create an automatically generated identifier and use the @Id annotation

CREATE TABLE PERSON ( SSN INT, NATIONALITY VARCHAR, NAME VARCHAR ) 
+6
source share
1 answer

Yes it is possible. A combined primary key consists of several primary key fields. Each primary key field must be one of the supported JPA types. For your table you have:

 @Entity @IdClass(PersonId.class) public class Person { @Id int ssn; @Id String nationality; .... } 

For an object with multiple keys, the JPA requires the definition of a special identifier class. This class must be attached to the entity class using the @IdClass annotation.

 class PersonId { int ssn; String nationality; } 

The ID class represents primary key fields, and its objects can represent primary key values

+10
source

Source: https://habr.com/ru/post/946611/


All Articles