Question

I try to get all the count of Articles (Article.class) which are not analyzed (analyzed == false). Sadly the following code returns absolutely wrong numbers. Would anybody know why?

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery(Long.class);
query.select(cb.count(query.from(Article.class)));
Root<Article> articles = query.from(Article.class);
Predicate condition = cb.isFalse(articles.get(Article_.analyzed));
query.where(condition);
TypedQuery<Long> unanalyzedArticlesAmount = entityManager.createQuery(query);
return unanalyzedArticlesAmount.getSingleResult();
Was it helpful?

Solution

finally read this post: How to count the number of rows of a JPA 2 CriteriaQuery in a generic JPA DAO?

and found the following solution:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery query = cb.createQuery();    
Root<Article> root = query.from(Article.class);
query.select(cb.count(root));
Predicate condition = cb.isFalse(root.get(Article_.analyzed));
query.where(condition);
TypedQuery<Long> unanalyzedArticlesAmount = entityManager.createQuery(query);
return unanalyzedArticlesAmount.getSingleResult();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top