我认为解决方案比看起来简单。您忘记了包含
cb.max ()在CriteriaBuilder子查询中。以下代码执行您要查找的查询。
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();final CriteriaQuery<Person> cq = cb.createQuery(Person.class);final Root<Person> root = cq.from(Person.class);cq.select(root);final Subquery<Integer> subquery = cq.subquery(Integer.class);final Root<Person> validityIDSQ = subquery.from(Person.class);subquery.select(cb.max(validityIDSQ.get(Person_.validityID)));subquery.groupBy(validityIDSQ.get(Person_.personID));cq.where(cb.in(root.get(Person_.validityID)).value(subquery));
此代码将创建以下查询:
select person0_.id as id1_0_, person0_.personID as personID2_0_, person0_.validityID as validity3_0_, person0_.value as value4_0_from person person0_where person0_.validityID in ( select max(person1_.validityID) from person person1_ group by person1_.personID)
我认为您正在使用Postgres。没有
cd.max()它会产生您引用的错误,因为您使用GroupBy而不使用聚合函数。我在Postgres和MySQL上进行了测试。两者兼具魅力。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)