jdbc 和 hibernate框架 分頁的思路
阿新 • • 發佈:2018-10-31
-
- 分頁: jdbc:
- –>
- executeQuery(String sql,PageBean pagebean,Class clz)
- sql:select from t_hibernate_book where book_name like ‘%?%’
-
select * from t_hibernate_book where book_name like '%西%'
-
countSql = select count(*) from (sql) t;
- 分頁: 1、sql–>countSql–>total–>pageBean
-
2、sql-->pageSql-->result
-
3、處理結果集
- hql:
-
0、select * from Book where bookName like '%:bookName%' select count(*)
-
sql from From frOm
-
1、hql-->countHql-->total-->pageBean
-
2、sql-->pageSql-->result(hibernate呼叫內建介面自動生成分頁語句,查詢結果) 3、不需要
- @author 海峰幾
*/
public class BaseDao { private void setParameter(Query query,Map<String, Object> map) { if(map ==null || map.size()==0) { return; } Object value = null; // 給query賦值 for(Map.Entry<String, Object> entry :map.entrySet()) { value = entry.getValue(); if(value instanceof Collection) { query.setParameterList(entry.getKey(), (Collection) value); } else if(value instanceof Object[]) { query.setParameterList(entry.getKey(), (Object[]) value); } else { query.setParameter(entry.getKey(), value); } } } private String getCountHql(String hql) { int index = hql.toUpperCase().indexOf("FROM"); return "select count(*)" +hql.substring(index); } public List executeQuery(String hql,PageBean pageBean,Map<String, Object> map,Session session){ if(pageBean != null && pageBean.isPagination()) { String countHql = getCountHql(hql); Query countQuery = session.createQuery(countHql); this.setParameter(countQuery, map); String total = countQuery.getSingleResult().toString(); pageBean.setTotal(total); Query pageQuery = session.createQuery(hql); this.setParameter(pageQuery, map); pageQuery.setFirstResult(pageBean.getStartIndex()); pageQuery.setMaxResults(pageBean.getRows()); return pageQuery.list(); }else { Query query = session.createQuery(hql); this.setParameter(query, map); return query.list(); } }