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;
}
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With