在web項目中,顯示數據一般采用分頁顯示的,在分頁的同時,用戶可能還有搜索的需求,也就是模糊查詢,所以,我們要在dao寫一個可以分頁并且可以動態加條件查詢的方法。分頁比較簡單,采用hibernate提供的分頁,動態條件采用map(“字段”,模糊值)封裝查詢條件,map可以添加多個查詢條件,是個不錯的選擇,從而達到實現分頁并模糊查詢。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
@Override public List<T> findPage( int page, int length, Map<String, Object> pram) { List<T> result = null ; try { //初始化hql,this.entityClazz.getSimpleName()是泛型的真實類名,在構造函數中獲取 String hql = "from " + this .entityClazz.getSimpleName() + " where 1=1 and " ; //注意空格 Session session = this .sesionFactory.openSession(); //獲取連接 if (!pram.isEmpty()) //判斷有無條件 { Iterator<String> it = 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) { throw re; } return result; } |
以上所述是小編給大家介紹的hibernate的分頁模糊查詢功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/liaohai/archive/2017/02/27/6472046.html