簡體   English   中英

如何在雙向關聯上禁用 Hibernate 外鍵約束?

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

我正在嘗試禁用在我的雙向關聯上生成的外鍵約束。 我已經設法為我所有的單向關聯做到了這一點,但由於某種原因,它在這里不起作用。

我知道最近在 Hibernate 5.x 中修復的ContraintMode.NO_CONSTRAINT的錯誤,並且我正在運行最新的 Hibernate 5.2.6。

我的注釋目前看起來像這樣:

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;
  }
}

但是盡管 NO_CONSTRAINT,Hibernate 仍然在 child.parent -> parent.id 上創建外鍵約束。

我還需要做些什么來抑制雙向情況下的外鍵?

謝謝!

這是 Hibernate 中的已知問題,請參閱https://hibernate.atlassian.net/browse/HHH-8805

解決方案是在映射端添加@org.hibernate.annotations.ForeignKey(name = "none")

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;
  }

}

注意:更喜歡 JPA 2.1 引入的javax.persistence.ForeignKey代替。 不推薦使用本機注釋。

除了@ Bustanil Arifin 的回答:

您可以通過以下方式組合@OneToMany@javax.persistence.ForeignKey

class Parent {

  @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
  @JoinColumn(name = "parent", foreignKey = @javax.persistence.ForeignKey(name = "none"))
  public List<Child> getChildren() {
    return children;
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM