【问题标题】:Hibernate/JPA: Get one (first) element of a OneToMany relationshipHibernate/JPA:获取 OneToMany 关系的一个(第一个)元素
【发布时间】:2014-11-20 17:08:37
【问题描述】:

我有一个 OneToMany 关系,假设 ListGroup 拥有许多 ListItems。我定义了 OneToMany 字段并且它可以工作,但我并不总是想要获得所有 ListItems。我想要一个名为latestItem 的附加字段。在 Hibernate 中,当您访问 oneToMany 集合中的一个元素时,它会获取所有元素,这就是我想要这个额外映射的原因。如果有很多项,以下是低效的:

public ListItem getFirstItem() {
    return listItems.get(0);
}

我试图建立一个公式。如果我想获取相关字段的单列,公式似乎可以工作,如下所示:

@Formula("(select A.description from LIST_ITEM A where A.list_group_id=id and A.id=(select max(B.id) from LIST_ITEM B where B.list_group_id=id))")
public String getLatestListItemDescription() { ... }

但是,如果我尝试选择整行放入一个 bean 中,它会失败:

@Formula("(select A.* from LIST_ITEM A where A.list_group_id=id and A.id=(select max(B.id) from LIST_ITEM B where B.list_group_id=id))")
public ListItem getLatestListItem() { ... }

Caused by: org.hibernate.MappingException: Could not determine type for: ListItem, at table: LIST_GROUP, for columns: [org.hibernate.mapping.Formula( (select A.* from LIST_ITEM A where A.list_group_id=id and A.id=(select max(B.id) from LIST_ITEM B where B.list_group_id=id)) )]

即使我有 ListItem 的注释,将其映射到 LIST_ITEM 表。

这对于公式来说是不可能的,还是有其他方法可以解决这个问题?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    可能应该使用select A from LIST_ITEM A 而不是select A.* from LIST_ITEM A

    附言哈哈,我来晚了

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多