3

我正在尝试删除父表行并观察它是否在子表行上级联(删除)。带有 java 注释的父子表实体是:

//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();

如果我删除孩子然后尝试删除父表行,它工作正常。寻求帮助以插入工作方式一次删除父表和子表行。与创建分配数据和插入的 ParentTable 对象一样,插入父表和子表行。谢谢您的帮助。

4

2 回答 2

1

不幸的是,JPQL 中的 DELETE 子句不会级联到相关实体,因此您需要使用 API 进行级联删除或更新:

A delete operation only applies to entities of the specified class and its subclasses. 
It does not cascade to related entities.
于 2013-04-09T06:38:59.043 回答
0

回答我的问题以在删除父表行时删除子表行。

父表对象到 getChildTableSet 的映射:

@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "parentTable", orphanRemoval = true)
public Set<ChildTable> getSetChildTable() {
    return setChildTable;
}

ParentTable 列的子表对象的映射:

@ManyToOne
@JoinColumn(name = "PARENT_TABLE_ID")
public ParentTable getParentTable() {
    return parentTable;
}

其余的 getter 和 setter 方法保持不变,两个父子表的 ID 都是自动生成的,只需获取映射,其余的应该可以正常工作。

于 2013-05-23T00:01:41.827 回答