1

经过我们的搜索,我仍然无法找到在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

我尝试了连接、多选等。我需要在likegetResultList()中返回我。ListListlist[0] - (Preke)preke1, list[1] - (Integer)count1; list[0] - (Preke)preke2, list[1] - (Integer)count2 ...

编辑 1

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");
    ...
}

它给了我以下 JPQL 声明:

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 ?, ?

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

如上面JPQL语句所说——t1.prid = t0.prid应该是坏的部分,如何替换它?我想我在这里需要的是一个LEFT JOIN. 但是怎么做呢?

4

1 回答 1

1

而不是使用

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

尝试使用

Join<Preke, Nuotrauka> images = from.join("images", JoinType.LEFT);
Expression<Long> count = cb.count(images);
于 2012-11-09T13:32:20.420 回答