hibernate 分页操作(防代码注入)

新建一个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());
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值