Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
like image 345
Anders Pedersen Avatar asked Dec 14 '16 13:12

Anders Pedersen


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 a primary key have multiple fields?

Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.

Can a JPA entity have multiple Onetomany associations?

You can have multiple one-to-many associations, as long as only one is EAGER.


2 Answers

You need to have a class for your composite key:

public class CompositeKey implements Serializable {     private int column1;     private int column2;     private int column3; } 

and then in your entity class use the @IdClass annotation:

@Entity @IdClass(CompositeKey.class) public class EntityExample {     @Id     private int column1;     @Id     private int column2;     @Id     private int column3;     ...     ... } 

I think this should work. Hope it helps, cheers!

Yea and there is the other solution, the one that @jklee mentioned, both work, it's a matter of preference.

like image 146
Raul Cuth Avatar answered Sep 26 '22 03:09

Raul Cuth


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_

like image 26
jklee Avatar answered Sep 22 '22 03:09

jklee