1. 程式人生 > >Hibernate多條件模糊分頁查詢

Hibernate多條件模糊分頁查詢

因為要做一個分頁的功能,所以就上網隨便找了一個hibernate分頁的例項,但是總是報出:
org.hibernate.QueryParameterException: could not locate named parameter這個惱人的錯誤,卻又查不到到底是那裡錯了。
仔細想一想,錯誤提示是因為我的引數沒有設定,就是我沒有那個引數,但是我卻給它賦值了。
因為一般我們都用 query.setParameter(arg0, arg1)給hql語句新增引數。那麼為什麼不自己寫一個完整的SQL語句直接呼叫
Query query =session.createQuery(hql);
下面是整個程式碼:
注:Employee是一個實體型別
pageNo是頁碼
pageSize是分頁大小
hql=”from “+實體名
Map裝的是實體對應的屬性和屬性對應的值
為了不花費功夫處理開頭和結尾的where和and 問題,我添加了兩個永真的表示式1=1 ,2=2
簡單說當傳入的map為空時,那麼hql=“from Employee where 1=1 and 2=2”;
注意空格問題

public List<Employee> findPageByQuery(int pageNo, int pageSize, String hql, Map<String,Object> map)   
 {   
     List<Employee> result = null;   
     try  
     {  
      hql+=" where 1=1 and ";
      Session session=HibernateSessionFactory.getSession();
      if(!map.isEmpty())
      {
       Iterator<
String> it=map.keySet().iterator(); while(it.hasNext()) { String key=it.next(); hql=hql+key+" like "+"'%"+map.get(key)+"%'"+" and "; }//where stationName like '%"+stname+"%'" } hql+=" 2=2"; System.out.println(hql); Query query =session.
createQuery(hql); query.setFirstResult((pageNo - 1) * pageSize); query.setMaxResults(pageSize); result = query.list(); } catch (RuntimeException re) { throw re; } return result; }