Specifying restrictions "unique together" in Hibernate
I have an entity where I want to specify a restriction that two fields should have a unique pair value. E.g. one field is owner, another is name, I want a restriction that the combination of (owner,name) should be unique. But I do not want to make these a composite primary key:
@Entity
@Table(name="keyfile")
public class KeyFile {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@ManyToOne @ForeignKey开发者_运维问答(name="FK_SIGNATUREID_USER")
private User owner;
@Column(nullable=false,length=80)
private String name;
}
How do I specify this restriction with a Hibernate annotation?
Try the solution mentioned here:
https://forum.hibernate.org/viewtopic.php?p=2370666
Ergo it is
@Entity
@Table(name="keyfile",
uniqueConstraints = {@UniqueConstraint(columnNames={"owner", "name"})}
public class KeyFile { ... }
精彩评论