2012-08-07 36 views
0

我有一個Web應用程序訪問一個名爲「parent」的表的數據庫。這位家長有孩子也可以是多個孩子的家長:Hibernate - 來自OneToMany的父子關係的參考列

public class Thing extends Entity{ 

    @OneToMany(cascade = {CascadeType.ALL}) 
    @JoinColumn(name = "parent_id") 
    private List<Thing> children = new ArrayList<Thing>(); 

    @Column 
    private String property; 

    public String getProperty() { return property; } 
    public void setProperty(String property) { this.property = property; } 

實體已經拿到了PK屬性:

@Id 
@Column(nullable = false) 
@GeneratedValue(strategy = GenerationType.TABLE) 
private Long id; 

現在,我想從一個HQL查詢獲得的該PARENT_ID屬性事情。如果我只是做:

[Another class] 
Query queryParents = getEntityManager().createQuery("from Thing t where t.parent_id is null"); 

我得到一個錯誤說的屬性不存在。嗯,我添加以下Thing類:

@Column 
private Long parent_id; 
public Long getParent_id() { return parent_id; } 
public void setParent_id(Long parent_id) { this.parent_id = parent_id; } 

這似乎工作,但我認爲這是不正確的,因爲他們不引用同一實體......其實,試圖更新Thing對象將以「org.hibernate.StaleObjectStateException:Row被另一個事務更新或刪除(或未保存的值映射不正確):...」結束。

那麼,什麼是正確的方式來返回一個實體的「parent」的東西「物品」[數據庫有一個'parent_id'的對象物品],如果該類物品本身沒有得到該屬性?我是所有這些東西的newby ... 數據庫有一個每個Thing的parent_id字段,根父母爲null,並且包含其他所有內容的父ID。

在此先感謝。

回答

1

讓你聯想雙向的:

@OneToMany(mappedBy = "parent") 
private List<Thing> children; 

@ManyToOne 
@JoinColumn(name = "parent_id") 
private Thing parent; 

和查詢將只是

select t from Thing t where t.parent is null 

返回父ID將是:

Long parentId = thing.getParent() == null ? null : thing.getParent().getId(); 

瞭解更多關於雙向關聯的the Hibernate documentation

+0

感謝您的快速回答! 讓我們說,而不是「其中t.parent爲空」我說「其中t.parent是45」。我想通過它的parent_id返回「東西」,這是一個Long值。我有點失落,試圖做到這一點。 – Azurlake 2012-08-07 12:12:27

+0

'其中t.parent.id = 45'或者,如果你已經加載了具有ID 45的東西,其中t.parent =:parent','query.setParemeter(「parent」,theThingWithId45)'。 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-joins – 2012-08-07 12:14:50

+0

非常感謝。現在測試... – Azurlake 2012-08-07 12:21:23