title: How to soft delete parent and child together (cascade) using spring boot with jpa
body: <p>I have a project in which I am not allowed to delete records. Instead we soft delete them by updating a column(deleteFlag) in db which is common in all entities. I am trying achieve this using JPA in a generic way and I would like a JPA solution if possible. deleteFlag is the flag to soft delete which is set to Y or N.</p>
  
  <p>Code that I have written so far:</p>
  
  <p>Baseclass which all entities extend:</p>
  
  <pre><code>@MappedSuperclass
  public class BaseEntity implements Serializable {
  
  private static final long serialVersionUID = 1L;
  
  @Column(name = "CREATED_BY_C")
  private String createdByC;
  
  @Column(name = "CREATED_DATE_DT", updatable = false, insertable = false)
  private Timestamp createdDateDt;
  
  @Column(name = "UPDATE_DATE_DT", updatable = false, insertable = false)
  private Timestamp updateDateDt;
  
  @Column(name = "UPDATED_BY_C")
  private String updatedByC;
  
  @Column(name = "DELETE_FLG")
  private String deleteFlag;
  //getters and setters
  </code></pre>
  
  <p>BaseRepo which all CrudRepos extend:</p>
  
  <pre><code>    @NoRepositoryBean
      public interface BaseCrudRepository&lt;T extends BaseEntity, ID extends Serializable&gt;, CrudRepository&lt;T, ID&gt; {
  
  
      @Override
      @Query("select e from #{#entityName} e where e.deleteFlag !='Y'")
      public List&lt;T&gt; findAll();
  
      //Look up deleted entities
      @Query("select e from #{#entityName} e where e.deleteFlag ='Y'")
      public List&lt;T&gt; recycleBin(); 
  
      //Soft delete.
      @Query("update #{#entityName} e set e.deleteFlag='Y' where e.id=:id")
      @Modifying
      @Transactional
      public void softDelete(@Param("id")Integer id);     
  }
  </code></pre>
  
  <p>Sample entity which I am tyring to soft delete:</p>
  
  <pre><code>@Entity
  @Table(name = "SOME_PARENT_TABLE", schema = "SOME_SCHEMA")
  public class SomeParentTable extends BaseEntity {
  private static final long serialVersionUID = 1L;
  
  @Id
  @Column(name = "id_field")
  private Integer someParentTableId;
  
  //more fields here
  
  //bi-directional many-to-one association to SomeChildTable
  @OneToMany(mappedBy = "sdIncomingTransaction", , cascade=CascadeType.ALL)
  private List&lt;SomeChildTable&gt; someChildTables;
  </code></pre>
  
  <p>so when I do this:</p>
  
  <pre><code>someParentTableRepository.softDelete(someParentTableId);
  </code></pre>
  
  <p>only the someParentTable's deleteflag is marked Y. However, I wud like all the SomeChildTable associated with it to be soft deleted as well.</p>
  
  <p>Is there a way to achieve this? I m using spring data jpa. Feel free to ask for more details if required.</p>