I am trying to disable the foreign key constraint being generated on my bidirectional association. I have managed to do this for all my unidirectional associations, but for some reason it is not working here.
I do know about the bug with ContraintMode.NO_CONSTRAINT that was recently fixed in Hibernate 5.x, and I am running the latest Hibernate 5.2.6.
My annotations presently look like this:
class Parent {
@OneToMany(mappedBy="parent", cascade=CascadeType.ALL, orphanRemoval=true)
@OrderColumn(name="childIndex")
public List<Child> getChildren() {
return children;
}
}
class Child {
@ManyToOne(optional=false)
@JoinColumn(name="parent", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
public Parent getParent() {
return parent;
}
}
But despite NO_CONSTRAINT, Hibernate is still creating the foreign key constraint on child.parent -> parent.id.
Is there something additional I need to do to suppress the foreign key for the bidirectional case?
Thanks!
This is known issue in Hibernate, see https://hibernate.atlassian.net/browse/HHH-8805
Solution is to add @org.hibernate.annotations.ForeignKey(name = "none") on the mapped side.
class Parent {
@OneToMany(mappedBy="parent", cascade=CascadeType.ALL, orphanRemoval=true)
@OrderColumn(name="childIndex")
@org.hibernate.annotations.ForeignKey(name = "none")
public List<Child> getChildren() {
return children;
}
}
Note: Prefer the JPA 2.1 introduced javax.persistence.ForeignKey
instead. The native annotation is deprecated.
Addition to the @ Bustanil Arifin answer:
You can combine @OneToMany
and @javax.persistence.ForeignKey
in next way:
class Parent {
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name = "parent", foreignKey = @javax.persistence.ForeignKey(name = "none"))
public List<Child> getChildren() {
return children;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.