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

问题描述 投票:4回答:1

我有一个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表。

这对于Formulas来说是不可能的,还是有不同的方法可以解决这个问题?

java hibernate jpa
1个回答
0
投票

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

附:大声笑我迟到了一点

© www.soinside.com 2019 - 2024. All rights reserved.