Hibernate-父子关系中OneToMany的引用列

Hibernate-父子关系中OneToMany的引用列,hibernate,one-to-many,Hibernate,One To Many,我有一个web应用程序,它使用一个名为“parent”的表访问数据库。此父项具有子项,这些子项也可以是更多子项的父项: public class Thing extends Entity{ @OneToMany(cascade = {CascadeType.ALL}) @JoinColumn(name = "parent_id") private List<Thing> children = new ArrayList<Thing>(); @Colum

我有一个web应用程序,它使用一个名为“parent”的表访问数据库。此父项具有子项,这些子项也可以是更多子项的父项:

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; }
现在,我想从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:行被另一个事务更新或删除(或者未保存的值映射不正确):…”

那么,如果类对象本身没有属性,那么返回实体“Thing”[数据库有一列“parent\u id”作为对象对象]的parent\u id属性的正确方法是什么?我对这些东西都是新手。。。 数据库中的每一项都有一个parent_id字段,对于根父项为null,对于其他所有项都包含parent id


提前感谢。

让您的联系双向:

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

@ManyToOne
@JoinColumn(name = "parent_id")
private Thing parent;
返回父ID将是:

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

阅读中有关双向关联的更多信息。

感谢您的快速回答!让我们说“t.parent为空”而不是“t.parent为45”。我想通过它们的父id返回“Things”,这是一个长值。我试着这么做有点不知所措。
其中t.parent.id=45
或者,如果你加载了id为45的东西,
其中t.parent=:parent
query.setParemeter(“parent”,thingwitid45)
select t from Thing t where t.parent is null
Long parentId = thing.getParent() == null ? null : thing.getParent().getId();