有没有比执行 select 和 count 查询更有效的在 Hibernate 中进行分页的方法? [英] Is there a more efficient way of making pagination in Hibernate than executing select and count queries?
本文介绍了有没有比执行 select 和 count 查询更有效的在 Hibernate 中进行分页的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常分页查询看起来像这样.有没有更好的方法而不是制作两个几乎相等的方法,其中一个执行select * ...",另一个执行count * ..."?
Usually pagination queries look like this. Is there a better way instead of making two almost equal methods, one of which executing "select *..." and the other one "count *..."?
public List<Cat> findCats(String name, int offset, int limit) {
Query q = session.createQuery("from Cat where name=:name");
q.setString("name", name);
if (offset > 0) {
q.setFirstResult(offset);
}
if (limit > 0) {
q.setMaxResults(limit);
}
return q.list();
}
public Long countCats(String name) {
Query q = session.createQuery("select count(*) from Cat where name=:name");
q.setString("name", name);
return (Long) q.uniqueResult();
}
推荐答案
MySQLPerformanceBlog.com 的 Baron Schwartz 撰写了 post 关于这个.我希望这个问题有灵丹妙药,但没有.他提出的选项摘要:
Baron Schwartz at MySQLPerformanceBlog.com authored a post about this. I wish there was a magic bullet for this problem, but there isn't. Summary of the options he presented:
- 在第一次查询时,获取并缓存所有结果.
- 不要显示所有结果.
- 不要显示总数或其他页面的中间链接.仅显示下一个"链接.
- 估计有多少结果.
这篇关于有没有比执行 select 和 count 查询更有效的在 Hibernate 中进行分页的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文