Hello,
I'm having problem with creating code for successfully get count result for created query. I've managed to create code for PrimeFaces dataTable which uses CriteriaBuilder and stuff to generate sql query. Unfortunately I don't know how to get count result for created query. For example I can generate query:
Quote:
select id, name, surname from user where name like "Ad%"
But don't know how to do
Quote:
select count(*) from user where name like "Ad%"
My code looks like this:
Code:
List<User> users = new ArrayList<>();
DatabaseConnector dc = new DatabaseConnector();
EntityManager em = dc.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cc = cb.createQuery(User.class);
Root<User> u = cc.from(User.class);
if (sortField != null) {
Order o;
if (sortOrder == SortOrder.ASCENDING) {
o = cb.asc(u.get(sortField));
} else {
o = cb.desc(u.get(sortField));
}
cc.orderBy(o);
}
if (!filters.isEmpty()) {
List<Predicate> criteria = new ArrayList<Predicate>();
Iterator<Entry<String, String>> i = filters.entrySet().iterator();
while(i.hasNext()) {
Entry<String, String> e = i.next();
criteria.add(cb.like(u.<String>get(e.getKey()), e.getValue().concat("%")));
}
if(criteria.size() == 1) {
cc.where(criteria.get(0));
} else {
cc.where(cb.and(criteria.toArray(new Predicate[0])));
}
}
javax.persistence.Query q = em.createQuery(cc);
users = q.setMaxResults(pageSize).setFirstResult(first).getResultList();
maxResult = ???
return users;
I've saw some code which suppose to work, it used CriteriaBuilder (count method) along with CriteriaQuery (select method). But I can't make it works with my code. What am I doing wrong?