2017-04-05 40 views
0

我有兩個類,並對應它們兩個表。請假設所有的獲取者和設置者已被添加到類中。如何通過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; 

} 

現在,當我試圖刪除僱員實體,它成功地刪除它包括相關的地址實體。

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

在這裏,適當的填充DB後,當我嘗試用同樣的方法來刪除Employee實體,我得到以下異常:

org.hibernate.ObjectDeletedException:刪除的對象將通過級聯重新保存(從協會刪除已刪除對象)

我想這是因爲員工實體仍然以字段emps的形式在組織實體中被引用。我試圖找出解決方案,但沒有得到任何細節。

所以任何人都可以幫助我解決這個異常錯誤以及具體的理由?

回答

0

我的想法是嘗試並將orphanRemoval = true(在OneToMany - 行)Organization添加,然後只是將該員工從集中刪除。它應該很好地移除一切。

有點過時:https://docs.oracle.com/cd/E19798-01/821-1841/giqxy/

+0

你告訴我,我需要清除的領域,從組織實體環境管理計劃,並將其保存。所以相應的員工實體變成孤兒,因此會從數據庫中刪除? 因爲如果是的話,那麼我想在這裏提到我想使用deleteById(Long id)方法刪除一個員工。我不想刪除採用組織路線的員工實體! – gautam