EclipseLink Criteria API在连接表后计算结果

时间:2012-11-09 10:48:11

标签: java eclipselink criteria-api criteriaquery

在我们的搜索之后,我仍然无法找到在 EclipseLink条件查询中编写此SQL等效项的方法:

SELECT preke.*, count(nuotrauka.prid) AS cnt FROM preke LEFT JOIN nuotrauka ON nuotrauka.prid=preke.prid WHERE trash = 1 GROUP BY preke.prid ORDER BY cnt DESC

我尝试了加入,多选等等。我需要getResultList()List List内回复list[0] - (Preke)preke1, list[1] - (Integer)count1; list[0] - (Preke)preke2, list[1] - (Integer)count2 ...,如CriteriaBuilder cb = EntityManager.getInstance().getCriteriaBuilder(); CriteriaQuery criteriaQuery = cb.createQuery(Tuple.class); Root<Preke> from = criteriaQuery.from(Preke.class); Expression<Long> count = cb.count(from.get("images")); criteriaQuery.where(cb.equal(from.get("trash"), true)); criteriaQuery.multiselect(from.alias("preke"), count.alias("count")); criteriaQuery.groupBy(from.get("prid")); TypedQuery<Tuple> typedQuery = EntityManager.getInstance().createQuery(criteriaQuery); typedQuery.setFirstResult(PAGE * ITEMS_PER_PAGE); typedQuery.setMaxResults(ITEMS_PER_PAGE); prekes = typedQuery.getResultList(); ... for(Tuple t : prekes) { Preke p = (Preke)t.get("preke"); long count = (long)t.get("count"); ... }

编辑1

SELECT  t0.prid AS a1, 
        ..., 
        COUNT(t1.id) 
FROM    preke t0, 
        nuotrauka t1 
WHERE 
        ((t0.trash = ?) AND (t1.prid = t0.prid))
GROUP BY t0.prid LIMIT ?, ?

它给我以下JPQL语句:

t1.prid = t0.prid

这几乎没问题,但它不包括count为0的结果。

正如上面的JPQL声明所说 - LEFT JOIN应该是不好的部分,如何替换它?我想我需要的是{{1}}。但是怎么做呢?

1 个答案:

答案 0 :(得分:1)

而不是使用

Expression<Long> count = cb.count(from.get("images"));

尝试使用

Join<Preke, Nuotrauka> images = from.join("images", JoinType.LEFT);
Expression<Long> count = cb.count(images);