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;
}
A unique key is a set of single or multiple columns of a table that uniquely identify a record in a database table. Both the unique and primary key constraints provide a guarantee for uniqueness for a column or set of columns.
@UniqueConstraint annotation in Java.
We can set if the mapping column can have null value or if the column should have unique value. @Column(unique=true, nullable=false) private String name; The code above sets the name column to be unique and nullable.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With