-1

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;
}
  • are you sure, you don't mix up anything?? In your model: "child can exist without parent"/can have MANY parents! but "parent can't exist without child"/has min/max/exactly one child... – xerx593 Nov 10 '21 at 11:24
  • Yes I am sure, in my case Child can be used in other entities as well – Gevorg Harutyunyan Nov 10 '21 at 11:35
  • ..it is ok (it happened at least once in evolution! ..the "first child" had probably "no parent";), but the naming is confusing! (for english speakers:) – xerx593 Nov 10 '21 at 11:52

3 Answers3

1

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

Nadim
  • 43
  • 7
  • Sorry @Nadim it still not working after adding Cascade annotation. I have updated the post – Gevorg Harutyunyan Nov 10 '21 at 11:13
  • Just check the answer posted by xeex593 read the tutorial then you will fix it by yourself as per your need. Read both bi-directional and uni-directional – Nadim Nov 10 '21 at 12:40
0

Make the relation "bi-directional" by adding:

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

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

xerx593
  • 12,237
  • 5
  • 33
  • 64
0

After adding @OnDelete(action = OnDeleteAction.CASCADE) it solved my problem

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