一、控制分页Query的两个方法是什么?
一是:setFirstResult(int firstResult):设定从那个对象开始检索。
二是:setMaxResults(int maxResult):设置一次最多能检索出对象的数目。
public void QueryByPage(int pageSize) {
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
try {
sf = HibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
Query query = session.createQuery("select count(*) from User u ");
Number cnts = (Number) query.uniqueResult();
int UserCount = cnts.intValue();
int pageCount = 0;
pageCount = UserCount / pageSize;
if (UserCount % pageSize != 0) {
pageCount++;
}
Query query1 = session.createQuery("from User u");
for (int i = 0; i < pageCount; i++) {
System.out.println("第" + i + "页");
query1.setFirstResult(i * pageSize);
query1.setMaxResults(pageSize);
List<User> us = query1.list();
for (User u : us) {
System.out.println(u.toString());
}
}
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (ts != null) {
ts.rollback();
}
} finally {
session.close();
sf.close();
}
}
运行结果: