I am implementing "Advanced Search" kind of functionality for an Entity in my system such that user can search that entity using multiple conditions(eq,ne,gt,lt,like etc) on attributes of this entity. I am using JPA's Criteria API to dynamically generate the Criteria query and then using setFirstResult() & setMaxResults() to support pagination. All was fine till this point but now I want to show total number of results on results grid but I did not see a straight forward way to get total count of Criteria query.
This is how my code looks like:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Brand> cQuery = builder.createQuery(Brand.class);
Root<Brand> from = cQuery.from(Brand.class);
CriteriaQuery<Brand> select = cQuery.select(from);
.
.
//Created many predicates and added to **Predicate[] pArray**
.
.
select.where(pArray);
// Added orderBy clause
TypedQuery typedQuery = em.createQuery(select);
typedQuery.setFirstResult(startIndex);
typedQuery.setMaxResults(pageSize);
List resultList = typedQuery.getResultList();

我的结果集可能很大,所以我不想加载我的实体进行计数查询,所以请告诉我一种有效的方法来获取条件上的total count-like rowCount()方法(我认为它存在于Hibernate的条件中).

推荐答案

谢谢弗拉基米尔!

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Brand> cQuery = builder.createQuery(Brand.class);
Root<Brand> from = cQuery.from(Brand.class);
CriteriaQuery<Brand> select = cQuery.select(from);
.
.
//Created many predicates and added to **Predicate[] pArray**
.
.
CriteriaQuery<Long> cq = builder.createQuery(Long.class);
cq.select(builder.count(cq.from(Brand.class)));
// Following line if commented causes [org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.enabled' [select count(generatedAlias0) from xxx.yyy.zzz.Brand as generatedAlias0 where ( generatedAlias1.enabled=:param0 ) and ( lower(generatedAlias1.description) like :param1 )]]
em.createQuery(cq);
cq.where(pArray);
Long count = em.createQuery(cq).getSingleResult();
.
.
select.where(pArray);
.
.
// Added orderBy clause
TypedQuery typedQuery = em.createQuery(select);
typedQuery.setFirstResult(startIndex);
typedQuery.setMaxResults(pageSize);
List resultList = typedQuery.getResultList()

Though this is working fine but still I am not sure why I have to write

em.createQuery(cq);

to get it working. Any Idea?

Kotlin相关问答推荐

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

在 Kotlin 中实现并输入 Either

用于将 0.5 变为 0 的 round() 函数的模拟

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

如果带注释的成员未被特定块包围,则发出 IDE 警告

判断 Kotlin 变量是否为函数

使用事务时未调用 Kafka ConsumerInterceptor onCommit

如何在 jOOQ 中两次加入同一张表?

Kotlin 插件之间的区别

Kotlin spring boot @RequestBody 验证未触发

奇怪的 cotlin check Not Null 参数错误

.indices 在 kotlin 中的含义是什么?

比较 Kotlin 中的可比对象列表

如何在 android jetpack compose 中相互重叠列表项?

更新到版本4.10.1/4.10.2后 Gradle 同步失败

Android:Exoplayer - ExtractorMediaSource 已弃用

判断EditText是否为空kotlin android

Android studio,构建kotlin时出现奇怪错误:生成错误代码

函数引用和lambdas