0

我有一个 Web 应用程序使用名为“父”的表访问数据库。这个父母有孩子,也可以是更多孩子的父母:

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

这似乎有效,但我认为这是不正确的,因为它们没有引用同一个实体......事实上,试图更新一个事物对象,最终会出现“org.hibernate.StaleObjectStateException: Row was updated或被另一笔交易删除(或未保存的值映射不正确):...”。

那么,如果类 Thing 本身没有该属性,那么返回实体“Thing”的 parent_id 属性[数据库有一个对象 Thing 的列“parent_id”] 的正确方法是什么?我是所有这些东西的新手......数据库对于每个事物都有一个 parent_id 字段,对于根父级为空,并且包含其他所有内容的父级 ID。

提前致谢。

4

1 回答 1

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();

在Hibernate 文档中阅读有关双向关联的更多信息。

于 2012-08-07T12:09:19.400 回答