[hibernate分页查询]hibernate的分页模糊查询功能

更新时间:2021-06-30    来源:网页配色    手机版     字体:

【www.bbyears.com--网页配色】

在web项目中,显示数据一般采用分页显示的,在分页的同时,用户可能还有搜索的需求,也就是模糊查询,所以,我们要在dao写一个可以分页并且可以动态加条件查询的方法。分页比较简单,采用hibernate提供的分页,动态条件采用map(“字段”,模糊值)封装查询条件,map可以添加多个查询条件,是个不错的选择,从而达到实现分页并模糊查询。

 

 代码如下

@Override

  publicListfindPage(intpage,intlength, Mappram) {

     Listresult =null; 

     try

     {

          //初始化hql,this.entityClazz.getSimpleName()是泛型的真实类名,在构造函数中获取

       String hql ="from "+this.entityClazz.getSimpleName() +" where 1=1 and ";//注意空格

       Session session =this.sesionFactory.openSession();//获取连接

       if(!pram.isEmpty()) //判断有无条件

       {

         Iteratorit = pram.keySet().iterator();//迭代map

         while(it.hasNext())

         {

            String key = it.next();//获取条件map中的key,即条件字段

            hql = hql + key +" like "+"'%"+ pram.get(key) +"%'"+" and ";//将字段和模糊值拼接成hql

         }

       }

       hql +=" 2=2";//在hql末尾加上 2=2,方便hql再次拼接

       System.out.println(hql);

       Query query = session.createQuery(hql);

       query.setFirstResult((page -1) * length);//设置分页页码 

       query.setMaxResults(length); //设置每页数据长度

       result = query.list();//返回结果集

     }catch(RuntimeException re) 

     { 

       throwre; 

     } 

     returnresult; 

  }

 

本文来源:http://www.bbyears.com/wangyezhizuo/126884.html