2012-10-05 37 views
1

我有父母和孩子之間的關係(一對多/多對一)在我的代碼是這樣Hibernate的JPA從表中刪除的孩子當它從父集合和更新父

家長去除

@JsonAutoDetect 
@Entity 
@Table(name = "Parent") 
public class Parent{ 

    private Integer id; 
    private List<Child> childs; 

    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    @Column (name="idparent") 
    public Integer getId() { 
     return id; 
    } 
    public void setId(Integer id) { 
     this.id = id; 
    } 

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) 
    @LazyCollection (LazyCollectionOption.FALSE) 
    public List<Child> getChilds() { 
     return childs; 
    } 
    public void setChilds(List<Child> childs) { 
     for (Child child: childs) { 
      child.setParent(this); 
     } 
     this.childs= childs; 
    } 
} 

和孩子

@JsonAutoDetect 
@Entity 
@Table(name="Child") 
public class Child{ 

    private Integer id; 
    private Parent parent; 

    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    @Column (name = "idchild") 
    public Integer getId() { 
     return id; 
    } 
    public void setId(Integer id) { 
     this.id = id; 
    } 

    @ManyToOne(fetch = FetchType.EAGER) 
    @NotFound(action = NotFoundAction.IGNORE) 
    @JoinColumn(name = "idparent") 
    @JsonIgnore 
    public Parent getParent() { 
     return parent; 
    } 
    public void setParent(Parent parent) { 
     this.parent= parent; 
    } 
} 

一切正常,但是當我做somthink像

parent.getChilds().remove(child); 
session.update(parent); 

孩子is'nt從表中刪除,這是什麼問題,你能不能幫我請,對不起 我的英語不好:-(

+0

你已經有一個公認的答案,給出由Hibernate項目的主要開發人員之一......那麼爲什麼你重新打開這個問題? – overmeulen

回答

3

child不應該在這種情況下,數據庫中刪除。如果這是你想要的行爲,則需要啓用「孤兒去除」:

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval=true) 
@LazyCollection (LazyCollectionOption.FALSE) 
public List<Child> getChilds() { 
    return childs; 
} 
+0

我認爲這個解決方案是用來刪除所有孩子的時候刪除父母,但我想要的是從孩子表中刪除prent集合中刪除的孩子;當我更新父母。 – user820688

+1

你錯了。你如何嘗試它;) –

+0

是嘗試過但不工作:-( – user820688

0

它可能有助於

Child c = (Child) parent.getChilds(); 
parent.getChilds().remove(c); 
c.setParent(null); 

Child c = (Child) parent.getChilds(); 
parent.getChilds().remove(c); 
session.delete(c); 
相關問題