JPA 孤儿删除不适用于 OneToOne 关系 [英] JPA orphan removal does not work for OneToOne relations

查看:25
本文介绍了JPA 孤儿删除不适用于 OneToOne 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

这是示例域模型:

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

推荐答案

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

Cascading only makes sense for entity state transitions that propagate from a Parent to a Child. In your case, the Parent was actually the child of this association (having the FK).

尝试使用此映射:

@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);

或者更好的是,在 Parent 实体类中配置 setChild 方法来设置两个关联:

Or even better, confgiure the setChild method in the Parent entity class to set both associations:

public void setChild(Child child) {
    if (child == null) {
        if (this.child != null) {
            this.child.setParent(null);
        }
    }
    else {
        child.setParent(this);
    }
    this.child = child;
}

这篇关于JPA 孤儿删除不适用于 OneToOne 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆