Hibernate / JPA: get one (first) element of OneToMany relationship
I have a OneToMany relationship, say ListGroup
owns many ListItem
s. I have OneToMany field defined and it works, but I don't always want to get all ListItem
s. I want an additional field called latestItem
. In Hibernate, when you access one item in the oneToMany collection, it fetches all of them, so I want this additional mapping. If there are many items, the following is ineffective:
public ListItem getFirstItem() {
return listItems.get(0);
}
I tried to customize the formula. The formulas seem to work if I want to get a single column of the related field, for example:
@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() { ... }
However, if I try to select the entire string to be put into the bean, it doesn't work:
@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)) )]
Even though I have annotations on the ListItem that map it to the LIST_ITEM table.
Isn't this possible with formulas or is there some other way to do it?
source to share