[英]Foreign Key Violation on Delete and Update
我正在嘗試使用Java和Hibernate通過CRUD操作實現引用自身(同一類)的樹。 我的課是:
@Entity
@Table(name="Person")
public class Person implements Comparable<Person>{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@ManyToOne(cascade = {CascadeType.ALL})
private Person father;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
private List<Person> children = new ArrayList<Person>();
}
插入效果很好,每次插入時,我都會將人的父親設置為人,並將人添加為父親的孩子。 刪除時,如果刪除此人,則抱怨父親引用了該人的ID;如果刪除了父親,則抱怨人引用了父親的名。 那么,刪除或更新的正確步驟是什么? 有類似的問題,但是我找不到此雙向引用問題的確切解釋。
所以,由於@ Al1 mapped by
注解mapped by
,我找到了解決該問題的方法。 不過,在那之后,由於LazyInitializationException
,我無法檢索對象,但是能夠刪除樹中的葉子。 我通過更改private List<Person> children= new ArrayList<Person>();
解決了該問題private List<Person> children= new ArrayList<Person>();
到private Collection<Person> children = new LinkedHashSet<Person>();
該類現在看起來像:
public class Person implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@ManyToOne(cascade = {CascadeType.ALL})
private Person father;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, mappedBy= "father")
private Collection<Person> children = new LinkedHashSet<Person>();
}
為了刪除樹節點,我必須通過Hibernate.initialize(this.getChildren());
來加載子節點Hibernate.initialize(this.getChildren());
然后遞歸刪除每個節點。 我的刪除功能:
public static String deletePerson(Person p){
Transaction trns = null;
Session session = HibernateUtil.buildSessionFactory().openSession();
try {
trns = session.beginTransaction();
Hibernate.initialize(p.getChildren());
if (p.hasChildren()){
Collection<Person> children = p.getChildren();
for (Person person : children) {
deletePerson(person);
}
String hql = "delete from Person where name = :name";
session.createQuery(hql).setString("name", p.getName()).executeUpdate();
session.getTransaction().commit();
return "success";
}
else {
String hql = "delete from Person where name = :name";
session.createQuery(hql).setString("name", p.getName()).executeUpdate();
session.getTransaction().commit();
return "success";
}
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return "failure";
}
希望這對使用Hibernate和tree的人有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.