1

Let's say that this is a class that has unique constrained field.

@Entity
public class Thing {

   @Column(name = "name", unique = true)
   private String name;

   @ManyToOne
   private Owner owner;

}

Example works just fine if new Things are created with unique names. But when different owners want to create things with the same name this approach fails.

Is it possible to set unique constraint to differ records of Things in the database based on the Owners using Hibernate/JPA functionalities (I could not find any) or should I write my own logic and dump the unique from @Column.

Perhaps it could be done with Hibernate Validator? Reading the docs I haven't found much about unique constraints.

CAPS LOCK
  • 1,960
  • 3
  • 26
  • 41
  • 1
    I'm no Hibernate expert but in this question they deal with the same problem. Maybe this helps you http://stackoverflow.com/questions/2562746/jpa-entity-design-problem/2563009#2563009 – RubioRic Apr 05 '16 at 19:27
  • @RubioRic: interesting, I will examine it. – CAPS LOCK Apr 05 '16 at 19:57

1 Answers1

1

You're looking for @UniqueConstraint

http://docs.oracle.com/javaee/5/api/javax/persistence/UniqueConstraint.html

Michael Peacock
  • 2,011
  • 1
  • 11
  • 14
  • 1
    I don't see how could suggested annotation perform differently. It's used to define multiple constraints at the table level rather than at column level. I need more like cross-table solution. – CAPS LOCK Apr 05 '16 at 19:39
  • In your case, you don't want name to be unique, but the combination of name and owner to be unique. As it stands now, attempting to add a second thing with the same name as any existing thing will violate your one, column-level uniqueness constraint. – Michael Peacock Apr 06 '16 at 20:40
  • That makes more sense. So I could annotate `Thing` with something like `@UniqueConstraint(columnNames={"owner_id", "name"})`? – CAPS LOCK Apr 07 '16 at 08:56
  • It turns out that this really solves the problem. Answer accepted! – CAPS LOCK Apr 07 '16 at 09:18