0

I am not able to delete child entities when OneToMany relationship is with the same entity. Cascade is not working. If OneToMany relationship is between 2 different entities then cascade works fine. How to enforce cascade.delete when the relationship is between same entities. Cascade works fine during save.

@Entity
@Data
public class QuestionBank implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long questionBankId;
    
    private String questionSeriesId;
    
    private String questionShortText;
    
    
    @OneToMany(mappedBy="parentQuestionBank", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<QuestionBank> childQuestionBankList;
    
    @ManyToOne()
    private QuestionBank parentQuestionBank;

}

@DeleteMapping("/getQB/{id}")
public void deleteQB(@PathVariable Long id) {
        
    QuestionBank qb = queBankRepo.findById(id).get();
    queBankRepo.delete(qb);
}
mAsK
  • 189
  • 3
  • 9
  • Why do you use same entity for OneToMany relationship? – Geeth Feb 08 '22 at 06:50
  • The design demands to have an entity that is related to itself. I referred to this link to create the relationship. A question can have sub-questions or a question will not have sub-questions (parent-question) – mAsK Feb 08 '22 at 07:06
  • yes. I understood your problem. please try @OnDelete(action = OnDeleteAction.CASCADE) this annotation on childQuestionBankList parameter – Geeth Feb 08 '22 at 07:15
  • No this did not solve the issue. Only the parent is deleted. – mAsK Feb 08 '22 at 07:18

0 Answers0