'SQL JPA - Multiple columns as primary key

If i want severeal Column to make up an ID.

SQL example :

CONSTRAINT [PK_NAME] PRIMARY KEY ([Column1],[Column2],[Column3])

How can i do that with a Jpa Entity class ? through columndefinition ?

just setting the id field as:

value = Column1 + Column2 + Column3 // aint working.


Solution 1:[1]

Use @Embeddable and @EmbeddedId.

Example:

@Entity
public class Project implements Serializable {
    @EmbeddedId ProjectId id;
}
 
@Embeddable
class ProjectId implements Serializable {
    int departmentId;
    long projectId;
}

More information here http://www.objectdb.com/java/jpa/entity/id#Embedded_Primary_Key_

Solution 2:[2]

If all fields in the class are part of primary key, then solution would be pretty simple (extending solution provided by @raul-cuth):

@Entity
@IdClass(EntityExample.class)
public class EntityExample implements Serializable {

    @Id
    private int column1;

    @Id
    private int column2;

    @Id
    private int column3;
}

Solution 3:[3]

  1. Using @IdClass annotation on the @Entity class followed by @Id annotation on individual fields that are part of composite primary key.
  2. Alternatively can make use of @Embeddable class which can consist of individual fields of the composite primary key and then a reference of this class can be used as an attribute with @Embedded annotation in @Entity class. Hope this helps.

Solution 4:[4]

Be aware that the hibernate Entity-Class-to-SQL-DDL-Script generator will sort all the fields, and irrespective of the order in which it appears in the definitions, will create the table definition and the index / constraint definitions in this sorted order of the fields.

While the order of appearance of the fields in the table definition may not matter much, the order of fields in a composite index definitely do. So your key-fields must be named so that when sorted by their names they are in the order you desire for the index).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lorraine
Solution 2 heroin
Solution 3 M. Deinum
Solution 4 Alok P