Hibernate/JPA:获取 OneToMany 关系的一个(第一个)元素

Rya*_*lva 5 java hibernate jpa

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

public ListItem getFirstItem() {
    return listItems.get(0);
}
Run Code Online (Sandbox Code Playgroud)

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

@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() { ... }
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试选择要放入 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)) )]
Run Code Online (Sandbox Code Playgroud)

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

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

Sam*_*Sam 0

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

ps 哈哈 我迟到了一点