hibernate條件查詢加分頁封裝方法

@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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章