7

One can assign a primary key for its class by using @Id annotation in JPA. My question is what if one doesn't want to have an auto generated key in his tables and use fields (maybe more than one) as a primary key.

Let's say we have a person table with SSN, NATIONALITY and NAME. SSN is defined as the number a person is identified by in his country. Thus, we might have two persons with the same number in two different countries. The primary key for this table can be SSN+NATIONALITY. Is there any way to map these two fields using JPA and map it to an object? or the only way it to create an auto generated id and use @Id annotation

CREATE TABLE PERSON (
     SSN   INT,
     NATIONALITY VARCHAR,
     NAME VARCHAR
  )
sheidaei
  • 9,842
  • 20
  • 63
  • 86
  • Thanks for your feedback @femtoRgon. I leave it to the community to decide if it is a duplicate or not. However, reading the article you've linked, I have noticed it is about generating DDL files rather the basic question of how to annotate a composite key. – sheidaei Jun 05 '13 at 18:49

1 Answers1

11

Yes, it is possible. A composite primary key consist of multiple primary key fields. Each primary key field must be one of the supported by JPA type. For your table, you have:

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

For entity with multiple key, JPA requires defining a special ID class. 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 fields and its objects can represent primary key values

michal
  • 1,796
  • 1
  • 13
  • 11
  • 1
    The second option is to use `@EmbeddedId` - see [Oracle TopLink Docs](http://www.oracle.com/technetwork/middleware/ias/toplink-jpa-annotations-096251.html#EmbeddedId) for some examples. – Jens Birger Hahn Jun 05 '13 at 18:39
  • Thanks @michal. So if I got it correctly the first class will do the job? The second class that you have mentioned is for the case there weren't any composite key, right? – sheidaei Jun 05 '13 at 18:52
  • The first class 'Person' represents entity. PersonId specifies a composite primary key class that is mapped to multiple fields or properties of the entity. – michal Jun 05 '13 at 19:02