2013-04-09 134 views
2

我想刪除父錶行,並觀察它是否級聯(刪除)子錶行上。 父母與子女表實體Java註解是:QueryDSL,Hibernate刪除父錶行刪除父錶行

//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對象一樣,插入Parent表和Child錶行。 感謝您的幫助。

+0

添加的屬性orphanRemoval =真爲一對多的映射如下: '@OneToMany(級聯= {} CascadeType.ALL,的mappedBy = 「parentTable」,orphanRemoval =真)' 但並不能幫助 – 2013-04-09 02:51:54

+0

獲取下面的例外有和沒有子表cascade屬性: '@ManyToOne(級聯= CascadeType.ALL)' OR '@ ManyToOne' 異常線程 「main」 org.hibernate.exception.ConstraintViolationException:ERROR:更新或刪除表「PARENT_TABLE」違反了表「CHILD_TABLE」上的外鍵約束「fk7dfcef12c1324147」 細節:鍵(PARENT_TABLE_ID)=(1065)仍然引用自表「CHILD_TABLE」。 – 2013-04-09 03:02:03

回答

0

不幸的是DELETE子句JPQL不級聯到相關實體,所以你需要使用API​​進行級聯刪除或更新:

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

感謝Timo的回覆。 – 2013-04-09 23:19:11

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; 
} 

的獲取和設置方法的其餘部分保持不變,這兩個父 - 的ID的子表是自動生成的,只需要映射,其餘的應該可以正常工作。