Given is the following entity structure:
@Entity
public class Item {
@Id @GeneratedValue
private Long id;
@OneToMany
private Set<ItemEntry> itemEntries;
public Item() {
itemEntries = new HashSet<>();
}
// Getters and setters
}
@Entity
public class ItemEntry {
@Id @GeneratedValue
private Long id;
private String stringValue;
@ManyToOne
private Item item;
public Item() {}
// Getters and setters
}
This resolves to a database table ItemEntry as follows:
| id | stringValue | item_id |
I need to query this database table using the Criteria API in a JPA environment (persistence provider is Hibernate) and the canonical metamodel.
The query is to retrieve all distinct Item
objects where stringValue
is like %my%. Please note that a stringValue
that matches %my% might be assigned to the Item
multiple times.
What I have so far is the following code:
final CriteriaQuery<ItemEntry> itemEntryQuery = criteriaBuilder.createQuery(ItemEntry.class);
final Root<ItemEntry> itemEntryRoot = criteriaQuery.from(ItemEntry.class);
final Path<Item> selection = itemEntryRoot.get(ItemEntry_.item);
itemEntryQuery.select(selection).where(...).distinct(true);
The compiler issues an error stating
The method select(Selection<? extends ItemEntry>) in the type CriteriaQuery<ItemEntry> is not applicable for the arguments (Path<Item>)
Is there another possibility to achieve what I am looking for? At this point, I cannot use a SetJoin<Item, ItemEntry>
because I need to order the results by the stringValue
which is not possible as order by items need to appear in the select list for a distinct query. In case I use a SetJoin<Item, ItemEntry>
, only the the Item
's fields appear in the select clause.