简体   繁体   English

从休眠选择查询获取结果计数(查询返回的对象不是选择计数(*))

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

I am having an HQL query 我有一个HQL查询

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. 但是getCount方法要花费很多时间。 Say my table has 10000 rows and I am getting only 20 records at a time with the actual count. 假设我的表有10000行,而我一次只获得20条记录,且包含实际计数。 What is the fastest method to get count using the Query object. 什么是使用Query对象获取计数最快的方法。

I have tried this in the getCount function 我已经在getCount函数中尝试过

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 : 您必须设置以1开头而不是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 : 其次,要获取列表的大小,可以使用getResultList().size如下所示:

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

You should see what kind of sql is generated by hibernate. 您应该看到hibernate生成哪种类型的sql。 It can be very inefficient. 这可能是非常低效的。 If so you should write native sql query. 如果是这样,您应该编写本机sql查询。

Conventionally, you would have two queries, one to do a count(*) formally, and a second for the actual query. 按照惯例,您将有两个查询,一个查询正式执行count(*),第二个查询实际查询。 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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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