如何在删除child时删除parent实体?

How to delete parent entity when deleting child?

我有两个 类、Parent 和 Child。我想在删除 child 时删除 parent 实体。请注意 child 不应该知道 parent,所以我无法添加反向引用。

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

如果你说的是在删除子记录时删除父记录,那么你必须使用级联注解。

添加“双向”关系:

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

.. 到“Child”,然后添加一个 cascade。 (因此 Childdelete 将级联删除所有 Parents。)

  • Difference Between One-to-Many, Many-to-One and Many-to-Many?

  • When Vlad says so

添加@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;
}