tags:

views:

12

answers:

1

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?

+1  A: 

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 { ... }
Andreas
since owner is a foreign key, I had to change it to columnNames={"owner_id", "name"}
Carles Barrobés