在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 }