[英]How to delete an associate entities through Hibernate
我有兩個類,對應於兩個表。 請假定所有的獲取器和設置器都已添加到類中。
public class Employee implements Serializable {
//@ManyToOne( cascade = CascadeType.PERSIST, targetEntity = RackEntity.class )
//@Fetch( FetchMode.SELECT )
//@JoinColumn( name = "orgName", referencedColumnName = "orgName", nullable = true )
//private Organization org;
private Long id;
private string empName;
@LazyCollection( LazyCollectionOption.FALSE )
@OneToMany( mappedBy = "emp", cascade = { CascadeType.ALL } )
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST } )
private Set<Address> empAddress;
}
和
public class Address implements Serializable {
@ManyToOne( cascade = CascadeType.PERSIST, targetEntity = RackEntity.class )
@Fetch( FetchMode.SELECT )
@JoinColumn( name = "empName", referencedColumnName = "empName", nullable = true )
private Employee emp;
private Long id;
private String street;
private String block;
}
現在,當我嘗試刪除Employee實體時,它會成功刪除它,包括關聯的Address實體。
public void deleteById(Long id) {
logger.info("Deleting Employee {}", id);
Employee entity = (Employee) sessionFactory.getCurrentSession()
.get(Employee.class, id);
sessionFactory.getCurrentSession().delete(entity);
sessionFactory.getCurrentSession().flush();
}
但是,當我在引入另一個類,組織以及相應的表之后,取消對Employee類中的代碼進行注釋時,就會出現問題:
public class Organization implements Serializable {
private Long id;
private string orgName;
@LazyCollection( LazyCollectionOption.FALSE )
@OneToMany( mappedBy = "org", cascade = { CascadeType.ALL } )
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST } )
private Set<Employee> emps;
}
在這里,在適當地填充數據庫之后,當我嘗試使用相同的方法刪除Employee實體時,出現以下異常:
org.hibernate.ObjectDeletedException:刪除的對象將通過級聯重新保存(從關聯中刪除刪除的對象)
我猜這是因為Employee實體仍以emps字段的形式在Organization實體中被引用。 我試圖找出解決方案,但沒有得到任何詳細說明。
那么有人可以幫助我解決此Exception錯誤以及具體的理由嗎?
我的想法是嘗試將orphanRemoval = true
(在OneToMany
-Line中)添加到Organization
,然后僅從集合中刪除Employee。 它應該很好地刪除所有內容。
有點過時了: https : //docs.oracle.com/cd/E19798-01/821-1841/giqxy/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.