新建一个page类
public class Page {
private int queryPage = 0;
private int firstResult = 0;
private int maxPageSize = 10;
public Page(int queryPage) {
this.queryPage = queryPage >= 1 ? queryPage : 1;
}
public int getQueryPage() {
return queryPage;
}
public void setQueryPage(int queryPage) {
this.queryPage = queryPage;
}
public int getFirstResult() {
firstResult = (queryPage - 1) * maxPageSize;
return firstResult;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
public int getMaxPageSize() {
return maxPageSize;
}
public void setMaxPageSize(int maxPageSize) {
this.maxPageSize = maxPageSize >= 1 ? maxPageSize : 10;
}
}
方法
/***
* 分页数据操作
* @param objs 传递的对象
* @param types 传递的对象类型
* @param hql
* @param page
* @return
*/
public List getQueryPagnation(final Object[] objs, final Type[] types,
final String hql, final Page page) {
List tmpList = this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hql);
query.setParameters(objs, types);
query.setFirstResult(page.getFirstResult());
query.setMaxResults(page.getMaxPageSize());
return query.list();
}
});
return tmpList;
}
测试代码
@Test
public void TestPage()
{
Object[] objs = { "xxx", "xxx" };
Type[] types = new Type[] { Hibernate.STRING, Hibernate.STRING };
String hql = "from User model where model.name=? and model.password =?";
Page page = new Page(1);
page.setMaxPageSize(5);
System.out.println(getQueryPagnation(objs,types,hql,page).size());
}