Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: @OneToOne creates an implicit unique constraint with a randomly generated name. Is there any way to spcify that name in code using annotations?

In a Java class, I have this property

@OneToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private MyPropertyClass myProperty;

which not only creates a foreign key constraint, but a unique constraint also. This is the Hibernate DDL Schema output:

Hibernate: create table [...]
Hibernate: alter table [...] add constraint UK_nk1hqjkd7ln1f9a2pju1yy8ay  unique (myProperty)

Is there any way to specify the name of the unique constraint?

like image 217
Certainly Avatar asked Oct 17 '25 23:10

Certainly


1 Answers

Please try uniqueConstraints attribute of @Table annotation in the class level.

@Table( name ="tablename " , uniqueConstraints={
       @UniqueConstraint(name="myconst", columnNames={"myProp"})
   })

public class MyEntity {

@OneToOne(fetch = FetchType.EAGER, cascade =     CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="myProp")
private MyPropertyClass myProperty;

}
like image 169
JPS Avatar answered Oct 20 '25 12:10

JPS