java - JPA Criteria 查询计数结果涉及连接

标签 java hibernate jpa pagination criteria-api

我正在使用 hibernate 和 JPA 标准 API,并尝试创建一个可重用的实用方法来确定查询将返回多少行。

目前我有这个:

Long countResults(CriteriaQuery cq, String alias){
    CriteriaBuilder cb = em().getCriteriaBuilder();
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    Root ent = countQuery.from(cq.getResultType());
    ent.alias(alias);
    countQuery.select(cb.count(ent));
    Predicate restriction = cq.getRestriction();
    if(restriction != null){
        countQuery.where(restriction);
    }
    return em().createQuery(countQuery).getSingleResult();
}

我像这样使用:
CriteriaBuilder cb = em().getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(modelClass());
root.alias("ct");
cq.select(root);

TypedQuery<User> query = em().createQuery(cq);
long count = countResults(cq, "ct");

这很好用。
但是,当我使用更复杂的查询时
Join<UserThing, Thing> j = root.join(User_.things).join(UserThing_.thing);
cq.where(somePredicate);

我的电话 countResults()产生异常,如 org.hibernate.hql.internal.ast.InvalidPathException: Invalid path: 'myAlias.name' , <AST>:0:0: unexpected end of subtree , left-hand operand of a binary operator was null
我猜这与加入有关,并且我需要以某种方式对其进行别名,但到目前为止我还没有取得任何成功。

帮助?

最佳答案

我有同样的问题,我解决了:

CriteriaQuery<Long> countCriteria = cb.createQuery(Long.class);
Root<EntityA> countRoot = countCriteria.from(cq.getResultType());
Set<Join<EntityA, ?>> joins = originalEntityRoot.getJoins();
for (Join<EntityA, ?> join :  joins) {
    countRoot.join(join.getAttribute().getName());
}
countCriteria.select(cb.count(countRoot));
if(finalPredicate != null)
    countCriteria.where(finalPredicate);

TypedQuery<Long> queryCount = entityManager.createQuery(countCriteria);
Long count = queryCount.getSingleResult();

在哪里

originalEntityRoot 是我使用 where 子句进行查询的主根。

关于java - JPA Criteria 查询计数结果涉及连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600588/

相关文章:

java - 始终询问密码 KeyStore PKCS11

java - 以编程方式包含带有持久性单元的实体类?

hibernate - 在排序闭包中,如何最后获取空值?

java - 在mysql查询期间java代码中进行一些迭代后出现无限循环 "hangs"

java - Karaf/Maven - 无法解析 : missing requirement osgi. 接线包

hibernate - 如何使用 spring mvc 配置 ApacheSolr?

mysql - Hibernate 具有外键名称的多对一键

java - JPA映射: Reusing entities in multiple relationships

java - persistence.xml 缓存属性警告

google-app-engine - 使用 JPA 注释编码类时出现 JAXBException