java JPA 孤儿删除不适用于一对一关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31470414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:40:18  来源:igfitidea点击:

JPA orphan removal does not work for OneToOne relations

javahibernatejpaormspring-data-jpa

提问by ankurvsoni

Does anyone have a workaround for this issue: https://hibernate.atlassian.net/browse/HHH-9663?

有没有人对此问题有解决方法:https: //hibernate.atlassian.net/browse/HHH-9663

I am also facing a similar issue. When I created one-sided (no reverse reference) one to one relationship between two entities and set the orphan removal attribute to true, the referenced object is still in the database after setting the reference to null.

我也面临类似的问题。当我在两个实体之间创建单边(无反向引用)一对一关系并将孤儿移除属性设置为true时,将引用设置为null后,引用的对象仍在数据库中。

Here is the sample domain model:

这是示例域模型:

@Entity
public class Parent {
  ...
  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "child_id")
  private Child child;
  ...
}

@Entity
public class Child {
  ...
  @Lob
   private byte[] data;
  ...
}

I am currently working around this by manually deleting orphans.

我目前正在通过手动删除孤儿来解决这个问题。

采纳答案by Vlad Mihalcea

Cascadingonly makes sense for entity state transitionsthat propagate from a Parentto a Child. In your case, the Parent was actually the child of this association (having the FK).

级联仅对从Parent传播到Child 的实体状态转换有意义。在你的情况下,父母实际上是这个协会的孩子(拥有 FK)。

Try with this mapping instead:

尝试使用此映射:

@Entity
public class Parent {
  ...
  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent")
  private Child child;
  ...
}

@Entity
public class Child {

    @OneToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    ...
    @Lob
    private byte[] data;
    ...
}

And to cascade the orphan removal, you now need to:

要级联孤儿删除,您现在需要:

Parent parent = ...;
parent.getChild().setParent(null);
parent.setChild(null);

Or even better, use addChild/removeChild methods in the Parententity class:

或者更好的是,在Parent实体类中使用 addChild/removeChild 方法:

public void addChild(Child child) {
    children.add(child);
    child.setParent(this);
}

public void removeChild(Child child) {
    children.remove(child);
    child.setParent(null);
}

For more details, check out this article.

有关更多详细信息,请查看这篇文章