【问题标题】:How to delete parent entity when deleting child?删除子实体时如何删除父实体?
【发布时间】:2021-12-20 18:24:34
【问题描述】:

我有两个班级,Parent 和 Child。我想在删除孩子时删除父实体。请注意,孩子不应该知道父母,所以我不能添加反向引用。

        @Getter
@Setter
@Entity
@Table(name = "parent")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "child_id")
    private Child child;
}

    @Getter
@Setter
@Entity
@Table(name = "child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

修改后 这样还是不行

@Getter
@Setter
@Entity
@Table(name = "parent")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "child_id")
    private Child child;
}

@Getter
@Setter
@Entity
@Table(name = "child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

【问题讨论】:

  • 你确定,你没有混淆任何东西??在您的模型中:“孩子可以在没有父母的情况下存在”/可以有很多父母!但是“父母不能没有孩子”/有最小/最大/只有一个孩子......
  • 是的,我敢肯定,在我的情况下,Child 也可以在其他实体中使用
  • .. 没关系(它在进化中至少发生过一次!..“第一个孩子”可能有“没有父母”;),但命名令人困惑! (对于说英语的人:)

标签: java spring-boot hibernate hibernate-mapping


【解决方案1】:

如果您在删除子记录时谈论删除父记录,那么您必须使用级联注释。

【讨论】:

  • 抱歉@Nadim 在添加 Cascade 注释后它仍然无法正常工作。我已经更新了帖子
  • 只需检查 xeex593 发布的答案阅读教程,然后您将根据需要自行修复。双向读取和单向读取
【解决方案2】:

添加@OnDelete(action = OnDeleteAction.CASCADE) 后解决了我的问题

@Getter
@Setter
@Entity
@Table(name = "parent")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "child_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Child child;
}

@Getter
@Setter
@Entity
@Table(name = "child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

【讨论】:

    【解决方案3】:

    通过添加使关系“双向”:

    @OneToMany(mappedBy = "child", cascade = CascadeType.REMOVE)
    private List<Parent> parents;
    

    .. 到“Child”,并添加一个cascade。 (因此,Child 中的 delete 将级联删除所有 Parents。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多