views:

1518

answers:

2

I have two fields of an entity class which I don't want to be unique but to instead be used as composite fields for a key which must itself be unique. For example I have two fields (name and version) which can be the same for other records but together they must be unique. What is the best way to do that using Hibernate (with annotations)? I am using Hibernate Validator for other fields but I am not sure of a way to use that to validate that two fields together compose a unique key. I am using a generic entity class which has an id generic type which can be swapped out for a composite key class but I have yet to get that to work very well. Any tips would be appreciated, thanks in advance.

--James

+8  A: 

This will create a unique key on the database:

@Table( name = "MYTABLE",
        uniqueConstraints = { @UniqueConstraint( columnNames = { "NAME", "VERSION" } ) } )

This will be enforced by the database on a update or persist.

You'd need to write your own custom validator if you wanted to enforce this using Hibernate Validator.

mtpettyp
Thanks for this answer, it seems to work!
James Adams
A: 

We usually will wrap the two fields in an inner key class which is marked as @Embeddable. For example:

@Entity
public class Foo {

  @EmbeddedId()
  private Key key;
  ...

  @Embeddable
  public static class Key {
    @Column(nullable=false)
    private String name;
    @Column(nullable=false)
    private int version;

    protected Key () {
      // for hibernate
    }
    public Key (String name, int version) {
      this.name = name;
      this.version = version;
    }
    ...
    // You probably want .equals and .hashcode methods
  }
}
Gray