Query q = session.createQuery("from Cat as c"); q.setFirstResult(20000); q.setMaxResults(100); List l = q.list();那么Hibernate底层如何实现分页的呢?实际上Hibernate的查询定义在net.sf.hibernate.loader.Loader这个类里面,仔细阅读该类代码,就可以把问题彻底搞清楚。
Hibernate2.0.3的Loader源代码第480行以下:
if (useLimit) sql = dialect.getLimitString(sql);
public boolean supportsLimit() { return true; } public String getLimitString(String sql) { StringBuffer pagingSelect = new StringBuffer(100); pagingSelect.append(sql); pagingSelect.append(" limit ?, ?"); return pagingSelect.toString(); }
public boolean supportsLimit() { return true; } public String getLimitString(String sql) { StringBuffer pagingSelect = new StringBuffer(100); pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); pagingSelect.append(sql); pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?"); return pagingSelect.toString(); }