Home

Tuesday, February 22, 2011

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
Example:
@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;
}
I want to make a compound keys ("command", "model") as index, 
The Solution is @UniqueConstraint Annotation.
@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;
}
It's at all.

No comments:

Post a Comment