Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique constraints on members of embedded member in Hibernate

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;
}
like image 725
Joshua MN Avatar asked Jul 09 '14 18:07

Joshua MN


People also ask

What is unique key in hibernate?

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.

Which of the following annotations can be used to specify unique Rdbms constraints in entity classes?

@UniqueConstraint annotation in Java.

How do I make unique columns in JPA?

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.


1 Answers

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;
like image 76
Maciej Dobrowolski Avatar answered Sep 24 '22 07:09

Maciej Dobrowolski