【发布时间】:2016-07-08 10:24:43
【问题描述】:
给出以下实体结构:
@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
}
这将解析为数据库表 ItemEntry,如下所示:
| id | stringValue | item_id |
我需要在 JPA 环境(持久性提供程序是 Hibernate)和规范元模型中使用 Criteria API 查询此数据库表。
查询是检索所有 distinct Item 对象,其中 stringValue 类似于 %my%。请注意,与 %my% 匹配的 stringValue 可能会多次分配给 Item。
到目前为止,我有以下代码:
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 method select(Selection<? extends ItemEntry>) in the type CriteriaQuery<ItemEntry> is not applicable for the arguments (Path<Item>)
是否有另一种可能性来实现我正在寻找的东西?此时,我不能使用SetJoin<Item, ItemEntry>,因为我需要按stringValue 对结果进行排序,这是不可能的,因为按项目排序需要出现在不同查询的选择列表中。如果我使用SetJoin<Item, ItemEntry>,则只有Item 的字段出现在select 子句中。
【问题讨论】:
标签: hibernate criteria-api jpa-2.1