Question

Many to One :

When removing child object it shoud also remove parent object in Many-to-One relationship. While saving a single object in both parent and child it's working fine. But if I add more than one child object (2 or more) to one parent class, then how can I delete the child object from the list of child objects of one parent class?

Child POJO:

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Column(name="id")
  private int id;
  @Column(name="cName")
  private String cName;  

  @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
  @JoinColumn(name="pId")
  private Parent parent

Parent POJO:

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Column(name="id")
  private int id;
  @Column(name="pName")
  private String pName;
  @Column(name="address")
  private String address;
Was it helpful?

Solution

You will find the correct answer for your question in below link. There also same problem @kostja Explained very well.

How to delete Child or Parent objects from Relationship?

OTHER TIPS

You get the Iterator of the Collections object of children which is present in the Parent. Then using the iterator iterate to the specific child which you wish to remove and remove the child and update the parent object.

How are you mapping the parent to children. Currently you have just mapped your children to parent. But your parent is not mapped to the children. There are 2 options

  1. You can correct the parent mapping and add a set/list of children in parent.

    Set<ChildPojo> children;
    
  2. Or if your logic really needs such a broken mapping then you will have to first find all children which have the same parent and then delete the child which you wish to remove.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top