Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign several fields as a primary key of an entity (using JPA) [duplicate]

Tags:

java

orm

jpa

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
  )
like image 765
sheidaei Avatar asked Jun 05 '13 18:06

sheidaei


People also ask

How do I make two columns a primary key in JPA?

2. Composite Primary Keys. A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.

Can we have multiple @ID in JPA?

So yes, you can have more than one @Id. Or is it @EmbeddedId? I can't remember if @EmbeddedId is currently there, or if it is still in discussion by the JSR group for the next version of JPA. JPA 1.0 currently supports two different approaches for compound PKs.

Can a JPA entity have multiple Onetomany associations?

You can have multiple one-to-many associations, as long as only one is EAGER. But, even if you can use Set instead of List to bypass this MultipleBagFetchException , it's not a good thing to do because you'll end up with a Cartesian Product.


1 Answers

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

like image 70
michal Avatar answered Sep 23 '22 01:09

michal