zoukankan      html  css  js  c++  java
  • hibernate分页模糊查询

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

     1 @Override
     2     public List<T> findPage(int page, int length, Map<String, Object> pram) {
     3          List<T> result = null;   
     4          try  
     5          {  
               //初始化hql,this.entityClazz.getSimpleName()是泛型的真实类名,在构造函数中获取
    6 String hql = "from " + this.entityClazz.getSimpleName() + " where 1=1 and "; //注意空格
    7 Session session = this.sesionFactory.openSession(); //获取连接 8 if(!pram.isEmpty()) //判断有无条件 9 { 10 Iterator<String> it = pram.keySet().iterator(); //迭代map 11 while(it.hasNext()) 12 { 13 String key = it.next(); //获取条件map中的key,即条件字段 14 hql = hql + key + " like " + "'%" + pram.get(key) + "%'" + " and "; //将字段和模糊值拼接成hql 15 } 16 } 17 18 hql += " 2=2"; //在hql末尾加上 2=2,方便hql再次拼接 19 System.out.println(hql); 20 Query query = session.createQuery(hql); 21 query.setFirstResult((page - 1) * length); //设置分页页码 22 query.setMaxResults(length); //设置每页数据长度 23 result = query.list(); //返回结果集 24 25 } catch (RuntimeException re) 26 { 27 throw re; 28 } 29 30 return result; 31 32 }
  • 相关阅读:
    跃迁方法论 Continuous practice
    EPI online zoom session 面试算法基础知识直播分享
    台州 OJ 2648 小希的迷宫
    洛谷 P1074 靶形数独
    洛谷 P1433 DP 状态压缩
    台州 OJ FatMouse and Cheese 深搜 记忆化搜索
    台州 OJ 2676 Tree of Tree 树状 DP
    台州 OJ 2537 Charlie's Change 多重背包 二进制优化 路径记录
    台州 OJ 2378 Tug of War
    台州 OJ 2850 Key Task BFS
  • 原文地址:https://www.cnblogs.com/liaohai/p/6472046.html
Copyright © 2011-2022 走看看