Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound keys in JPA

I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?
I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.

In the following snippet, I need the command and model to be unique. pk is of course the primary key.

@Entity
@Table(name = "dm_action_plan")
public class ActionPlan {
    @Id
    private int pk;
    @Column(name = "command", nullable = false)
    private String command;
    @Column(name = "model", nullable = false)
    String model;
}
like image 897
homaxto Avatar asked Sep 18 '08 08:09

homaxto


People also ask

What is meant by compound key?

Compound keys are always made up of two or more primary keys from other tables. In their own tables, both of these keys uniquely identify data but in the table using the compound key they are both needed to uniquely identify data.

Can an entity have 2 primary keys?

The primary key of a relational table uniquely identifies each record in the table. So, in order to keep the uniqueness of each record, you cant have more than one primary key for the table.

What is @EmbeddedId in JPA?

Annotation Type EmbeddedIdApplied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable .


1 Answers

You can use @UniqueConstraint something like this :

@Entity
@Table(name = "dm_action_plan",
       uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } )
public class ActionPlan {
    @Id
    private int pk;

    @Column(name = "command", nullable = false)
    private String command;

    @Column(name = "model", nullable = false)
    String model;
}

This will allow your JPA implementation to generate the DDL for the unique constraint.

like image 81
Michel Avatar answered Oct 21 '22 08:10

Michel