-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: CriteriaBuilder and count result
PostPosted: Fri Nov 02, 2012 6:41 pm 
Newbie

Joined: Fri Nov 02, 2012 6:32 pm
Posts: 1
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?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.