javahibernateforeign-keyshibernate-annotations

How do I disable Hibernate foreign key constraint on a bidirectional association?


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!


Solution

  • 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.