orm – JPA 2.0:计数任意CriteriaQuery?
发布时间:2020-12-14 16:27:32 所属栏目:Java 来源:网络整理
导读:我试图实现以下便利方法: /** * Counts the number of results of a search. * @param criteria The criteria for the query. * @return The number of results of the query. */public int findCountByCriteria(CriteriaQuery? criteria); 在Hibernate中,
我试图实现以下便利方法:
/** * Counts the number of results of a search. * @param criteria The criteria for the query. * @return The number of results of the query. */ public int findCountByCriteria(CriteriaQuery<?> criteria); 在Hibernate中,这是完成的 criteria.setProjection(Projections.rowCount()); 在JPA中相当于上述什么?我发现了许多简单的计数示例,但是没有一个使用CriteriaQuery,其行数应该被确定. 编辑: 我不幸的发现,@帕斯卡尔的答案是不正确的.问题非常微妙,只有当您使用连接时才会出现: // Same query,but readable: // SELECT * // FROM Brain b // WHERE b.iq = 170 CriteriaQuery<Person> query = cb.createQuery(Person.class); Root<Person> root = query.from(Person.class); Join<Object,Object> brainJoin = root.join("brain"); Predicate iqPredicate = cb.equal(brainJoin.<Integer>get("iq"),170); query.select(root).where(iqPredicate); 当调用findCountByCriteria(query)时,它会死机,但有以下异常: org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.iq' [select count(generatedAlias0) from xxx.tests.person.dom.Person as generatedAlias0 where generatedAlias1.iq=170] 有没有其他方式提供这样的CountByCriteria方法? 解决方法
我写了一个实用类,JDAL JpaUtils来做:
> count results:Long count = JpaUtils.count(em,criteriaQuery); 等等… 如果您对源代码感兴趣,请参阅JpaUtils.java (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |