Search code examples
javahibernatejpaquerydsl

QueryDSL,Hibernate delete Child table row on delete of parent table row


I am trying to delete the parent table row and watching if it cascades (the delete) on the child table rows. Parent and Child Table Entity with java annotations are:

//Table details
@Entity
@Table(name="PARENT_TABLE")
//Mandatory Column details
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="PARENT_TABLE_ID")
private Integer id;
.
.
.
@OneToMany(cascade={CascadeType.ALL}, mappedBy = "parentTable")
private Set<ChildTable> setChildTable;
//Child table entity details:
@Entity
@Table(name = "CHILD_TABLE")
//Column details
@Id
@Column(name = "PARENT_TABLE_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
.
.
private ParentTable parentTable;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "PARENT_TABLE_ID")
public ParentTable getPatentTable() {
   return parentTable;
}

 //QueryDSL to Delete child table row, looks like this:
HibernateDeleteClause query = new HibernateDeleteClause(getSession(),QChildTable.childTable);
Path<?> idPath = QChildTable.childTable;
 query.where(((NumberPath<?>)idPath).in((Number[]) ids)).execute();
 //QueryDSL to Delete parent table rows, looks like this:
HibernateDeleteClause query = new HibernateDeleteClause(getSession(),QParentTable.parentTable);
Path<?> idPath = QParentTable.parentTable;
 query.where(((NumberPath<?>)idPath).in((Number[]) ids)).execute();

If i delete the child and then try to delete the parent table rows, it works fine. Looking for help to delete the Parent and Child table rows all at a time the way insert works. Like Creating ParentTable object assigning the data and insert , inserts both Parent table and Child table rows. Thanks for the help.


Solution

  • Unfortunately DELETE clauses in JPQL do not cascade to related entities, so you will need to use the API for cascading deletes or updates:

    A delete operation only applies to entities of the specified class and its subclasses. 
    It does not cascade to related entities.