title: Spring data jpa - While Updating a parent, how to delete the childs associated with it (based on id) from database and add the new child
body: <p>I have Parent entity Head and associated childs are Detail and Comment mapped using onetomany. I have only one DAO which is HeadDao. ProjectNumber PK in Head and FK in Detail and Comment. I'm trying to figure out how to delete the Child Comment using the projectNumber without writing the DAO for the child.</p>
  
  <p>Scenario is, while updating the Head i want to first delete the existing (associated) Comments from the database (using the projectNumber) and then add the new comments which are coming in the request. Could any one help me with this.
  Below are Entity classes (FYI Comment class has composite id, but i not pasted it here)</p>
  
  <pre><code>@Entity(name = "Head")
  @Table(name = "HEAD")
  public class Head {
  @Id
  @Column(name = "PRJ_NBR")
  private Integer projNumber;
  @JsonIgnore
  @OneToMany(mappedBy = "head",cascade = CascadeType.ALL,orphanRemoval = 
  true,fetch = FetchType.LAZY)
  private List&lt;Detail&gt; detailsList = new ArrayList&lt;Detail&gt;();
  
  @JsonIgnore
  @OneToMany(mappedBy = "head",cascade = CascadeType.ALL,orphanRemoval = 
  true,fetch = FetchType.LAZY)
  private List&lt;Comment&gt; commentsList = new ArrayList&lt;Comment&gt;();
  }
  
  @Entity
  @Table(name = "PRJ_CMT")
  @JsonIgnoreProperties
  public class Comment {
  @Transient
  private Integer projectNumber;
  
  @JsonIgnore
  @EmbeddedId
  private CommentCompositeId id;
  
  @JsonIgnore
  @ManyToOne
  @JoinColumn(name = "PRJ_NBR", updatable=false, insertable=false)
  private Head head;
  }
  
  @Transactional
  @Repository
  @PersistenceContext(type = PersistenceContextType.EXTENDED)
  public abstract interface HeadDao  extends JpaRepository&lt;Head, 
  Serializable&gt;
  {
   public abstract List&lt;Head&gt; findByProjNumber(Integer paramInteger);
  
   public abstract List&lt;Head&gt; findAll();
  
    @SuppressWarnings("unchecked")
    public abstract Head saveAndFlush(Head paramHead);
  
    public abstract List&lt;Head&gt; findByCusSysId(Integer paramInteger);
  
    public abstract Integer deleteByProjNumber(Integer projNumber);
   }
  
   While adding i'm using below code
  this.headDao.saveAndFlush(head);
  </code></pre>