創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!
在web項(xiàng)目中,顯示數(shù)據(jù)一般采用分頁(yè)顯示的,在分頁(yè)的同時(shí),用戶可能還有搜索的需求,也就是模糊查詢,所以,我們要在dao寫(xiě)一個(gè)可以分頁(yè)并且可以動(dòng)態(tài)加條件查詢的方法。分頁(yè)比較簡(jiǎn)單,采用hibernate提供的分頁(yè),動(dòng)態(tài)條件采用map(“字段”,模糊值)封裝查詢條件,map可以添加多個(gè)查詢條件,是個(gè)不錯(cuò)的選擇,從而達(dá)到實(shí)現(xiàn)分頁(yè)并模糊查詢。
@Override public ListfindPage(int page, int length, Map pram) { List result = null; try { //初始化hql,this.entityClazz.getSimpleName()是泛型的真實(shí)類名,在構(gòu)造函數(shù)中獲取 String hql = "from " + this.entityClazz.getSimpleName() + " where 1=1 and "; //注意空格 Session session = this.sesionFactory.openSession(); //獲取連接 if(!pram.isEmpty()) //判斷有無(wú)條件 { Iterator 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); //設(shè)置分頁(yè)頁(yè)碼 query.setMaxResults(length); //設(shè)置每頁(yè)數(shù)據(jù)長(zhǎng)度 result = query.list(); //返回結(jié)果集 } catch (RuntimeException re) { throw re; } return result; }