欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdbc 和 hibernate框架 分页的思路

程序员文章站 2024-03-13 22:21:34
...
    • 分页: 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();
		}
	}
相关标签: CSDN