【发布时间】:2017-10-08 17:22:30
【问题描述】:
我有一个 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();
}
但是 getCount 方法花费了很多时间。假设我的表有 10000 行,而我一次只得到 20 条记录的实际计数。使用 Query 对象获取计数的最快方法是什么。
我已经在 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;
}
但是如何在新查询中设置参数?有没有办法只更改查询对象中的查询字符串。
【问题讨论】:
-
不清楚:标题中有“(查询返回对象不选择计数(*))”你的意思是你不能使用计数查询?
-
是的,我在 getCount 函数中只有查询对象。我可以获取查询字符串并对其进行更改以进行计数查询,但我还是不知道如何构建新查询
-
所以...如果您实际上可以获取查询并替换它...只需进行自己的查询并完成它?这就像拿一把锤子剪东西,当你可以抓住一把剪刀时尝试磨它
-
是的。我刚刚编辑了问题并添加了我想要做的事情。在 Query 对象中,我需要单独编辑查询字符串