Unique constraints on members of embedded member in Hibernate

hibernate, java, jpa

Solution

It is possible by using:

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"i1", "i2"})})
public class Widget {

It would result in `CREATE` SQL (postgresql example)

create table Widget 
(  id int8 not null,
   i1 int8, 
   i2 int8 ,
   primary key (id),
   unique (i1, i2)
) 

Optionally - it would be probably more consise and readable when you add `@AttributeOverride` annotation specyfying in one file - column names for both attributes

@AttributeOverrides({
        @AttributeOverride(name = "i1", column = @Column(name = "i1")),
        @AttributeOverride(name = "i2", column = @Column(name = "i2"))
})
@Embedded
Nested nested;

Problem

Is it possible to define unique constraints on members of an embedded class in Hibernate? I need to be sure that Nested::i1 and Nested::i2 are unique as a pair (the combination) ``` @Entity @Table( uniqueConstrains = ???) public class Widget { @Id private int id; @Embedded Nested nested; } @Embeddable public class Nested { private int i1; private int i2; } ```

Original source