Home > Mobile >  How to delete parent entity when deleting child?
How to delete parent entity when deleting child?

Time:11-11

I have two classes, Parent and Child. I would like to delete the parent entity when removing a child. Note that child should not know about the parent, so I couldn't add backreference.

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

After edit This way it still not working

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

CodePudding user response:

If you talking about deleting parent record when child record is deleted then you must use Cascade annotation.

CodePudding user response:

Make the relation "bi-directional" by adding:

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

.. to "Child", and add a cascade to that. (So a delete of a Child will cascade the removal of all it's Parents.)

  • Related