使用CriteriaBuilder选择“where”计数

时间:2015-05-08 13:24:31

标签: hibernate jpa orm

我正在尝试做这样的事情

SELECT COUNT(*) FROM Tickets WHERE ticketStatus = 3 AND ...

但仅使用JPA提供的CriteriaBuilder。这就是我所拥有的:

private class Criteria {
    CriteriaBuilder builder;
    CriteriaQuery<TicketModel> query;
    Root<TicketModel> root;

    public Criteria() {
        builder = em.getCriteriaBuilder();
        query = builder.createQuery(TicketModel.class);
        root = query.from(TicketModel.class);
    }
}
public long getSearchResultsQuantity(SearchModel search) {
    Criteria c = new Criteria();
    List<Predicate> params = new ArrayList<Predicate>();

    if (search.getStartDate() != null && search.getEndDate() != null) {
        params.add(c.builder.between(c.root.get(TicketModel_.ticketDate), search.getStartDate(),
                search.getEndDate()));
    }

    if (search.getStatus() != -1) {
        params.add(c.builder.equal(c.root.get(TicketModel_.ticketStatus), search.getStatus()));
    }

    CriteriaQuery<Long> q = c.builder.createQuery(Long.class);

    return em.createQuery(
            q.select(c.builder.count(q.from(TicketModel.class))).where(params.toArray(new Predicate[] {})))
            .getSingleResult();
}

但是,当我尝试执行此查询时,我收到了这样的异常:

org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.ticketStatus' [select count(generatedAlias0) from com.mif.spring.models.TicketModel as generatedAlias0 where generatedAlias1.ticketStatus=0]

我在春天有点不高兴,所以任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

问题是你在混合根。

如果为两个根创建相同的别名将起作用。

例如:

private class Criteria {
    CriteriaBuilder builder;
    CriteriaQuery<TicketModel> query;
    Root<TicketModel> root;


    public Criteria(String alias) {
        builder = em.getCriteriaBuilder();
        query = builder.createQuery(TicketModel.class);
        root = query.from(TicketModel.class);
        root.alias(alias);
    }
}

然后

 Criteria c = new Criteria("someAlias");
 ...
 CriteriaQuery<Long> q = c.builder.createQuery(Long.class);
 Root<TicketModel> root = q.from(TicketModel.class);
 root.alias("someAlias");

 return em.createQuery(
         q.select(c.builder.count(root)).where(
params.toArray(new Predicate[] {})))
                .getSingleResult();

也许你可能对我可以做的课程JpaUtils(我写的)感兴趣:

Long count = JpaUtils.count(em, criteria);

从任何条件查询中获取计数。