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!
To disable a foreign key constraint for INSERT and UPDATE statements. In Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu.
Bidirectional joins are used in circumstances where the data between 2 joined tables needs to flow in both directions. In a unidirectional join, the data flows in a single direction from the primary table (the table containing the primary key column) to the foreign table (the table containing the foreign key column).
Use @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations. From Hibernate manual: The @PrimaryKeyJoinColumn annotation does say that the primary key of the entity is used as the foreign key value to the associated entity.
Bidirectional association allows us to fetch details of dependent object from both side. In such case, we have the reference of two classes in each other. Let's take an example of Employee and Address, if Employee class has-a reference of Address and Address has a reference of Employee.
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.
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