考虑以下假设模型:
@Entity
class Parent{
Integer number;
Child1 child1;
Child2 child2;
String description;
}
@Entity
class Child1{
Integer id;
}
@Entity
class Child2{
Integer id;
}
我正在构建一个查询,该查询对 Parent
中的 number
执行聚合函数,但我还想显示 child1
和 child2
,因此我将它们包含在条件生成器的 group by 子句中。由于其他一些随机原因,我正在创建一个 Tuple
查询。
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Parent> root = cq.from(Parent.class);
cq.select(cb.tuple(root.get("description"),
root.get("child1")
cb.count(root.get("number")));
cq.groupBy(root.get("description"),
root.get("child1")));
当我执行此查询时,出现错误:“child1.id 包含在 SELECT 中,但未包含在 group by 子句中,并且不是聚合函数的一部分”。每当我从实体 Parent
中选择不是实体本身的字段时,我就没有遇到任何问题。一旦我尝试从类 Parent
中选择一个本身是实体的字段,那么我就会遇到这个麻烦,即使我将其包含在 group by 子句中。我什至尝试过这样做,但没有运气:
cq.groupBy(root.get("description"),
root.get("child1").get("id")));
如何创建一个执行我想要执行的操作的 CriteriaQuery
?有什么解决办法吗?
最佳答案
除了执行分组依据的字段外,我们必须对表中的所有字段使用聚合函数。 因此,在您的情况下,您只能使用以下函数从实体中选择值。
AVG() - Returns the average value.
COUNT() - Returns the number of rows.
FIRST() - Returns the first value.
LAST() - Returns the last value.
MAX() - Returns the largest value.
MIN() - Returns the smallest value.
SUM() - Returns the sum.
如果没有聚合函数,您不能按数字分组并选择 child1。 希望这会有所帮助。
关于java - 在 CriteriaBuilder 查询的 groupBy 子句中包含实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494923/