简体   繁体   中英

Get count of results from hibernate select query (query returning an object not Select count(*))

I am having an HQL query

String q = "From TMainTable where a= ? and b= ? and c=?"
Query q = session.createQuery(q).setParameter(0,1).setParameter(1,2).setParameter(2,3);
int count = getCount(q);
List<TMainTable> list = q.setFirstResult(pageNo).setMaxResults(maxLimit).list()

public int getCount(Query q){
   return q.list().size();
}

But the getCount method is taking so much of time. Say my table has 10000 rows and I am getting only 20 records at a time with the actual count. What is the fastest method to get count using the Query object.

I have tried this in the getCount function

public Long getCount(Query q){
String queryString = q.getQueryString();
            String countQueryString = "Select count(*) From "+queryString.substring(0, q.getQueryString().indexOf(" From"));
            System.out.println(countQueryString);
            Long c= (Long)ctx.getSession().createQuery(countQueryString).uniqueResult();
return c;
}

But how can I set the parameters in the new query ? Is there a way I can alter only the query string in Query Object.

You have to set parameters starting with 1 not with 0 :

Query q = session.createQuery(q).setParameter(0,1).setParameter(1,2).setParameter(2,3);
//--------------------------------------------^-----------------^-----------------^

Instead you have to use :

Query q = session.createQuery(q).setParameter(1,1).setParameter(2,2).setParameter(3,3);
//--------------------------------------------^-----------------^-----------------^

Second to get size of your list, you can use getResultList().size like this :

public int getCount(Query q){
   return q.getResultList().size();
}

You should see what kind of sql is generated by hibernate. It can be very inefficient. If so you should write native sql query.

Conventionally, you would have two queries, one to do a count(*) formally, and a second for the actual query. The only way that the main query can get the number of results is by fully executing and then doing a count on the result list, which will be very slow.

Try this out :

  Query query = session.createQuery("select count(*) from Class_NAME as a where YOUR_CONDITION");
        try {
            return Integer.valueOf(String.valueOf(query.uniqueResult()));
        } catch (Exception e) {
            //Print stacktrace
            return 0;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM