HQL通用查询带分页

1.查询方法的提取 

package com.zking.eight.dao;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.query.Query;


public class BaseDao {
	
	/**
	 * 
	 * @param query 预定义对象
	 * @param map  前台传递过来的参数
	 */
	private void setParamenter(Query query,Map<String, Object> map) {
		if(map == null || map.size() == 0 ) {
			return;
		}
		//赋值:
		Object value = null;
		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);
			}
		}
	}
	
	/**
	 * sql = select * from t_hibernate_book where book_name like '%不温不火%' 
	 * countSql = select count(*) from (select * from t_hibernate)
	 * pagesql = sql +"limit ?, ?" hibernate中这一步省略
	 * 
	 * hql= from Book where bookName like '%不温不火%'
	 * hql =select bookName,price from Book where bookName like '%不温不火%'
	 * 
	 * 思路:
	 * 截取from 后面的sql 语句,前面拼接select count(*)
	 * from From froM
	 * 
	 * 全部转大写
	 * 
	 */
	
	/**
	 * 将from转大写,便于拼接
	 * @param hql
	 * @return
	 */
	public String getCountHql(String hql) {
		int index = hql.toUpperCase().indexOf("FROM");
		return "select count(*) "+hql.substring(index);
	}
	
	public List executeQuery(Session session,String hql,PageBean pageBean,Map<String, Object> map) {
		//判断是否分页
		if(pageBean != null && pageBean.isPagination()) {//分页
			String countHql = getCountHql(hql);
			Query CountQuery = session.createQuery(countHql);
			//获取到参数
			this.setParamenter(CountQuery, map);
			//pageBean中存放总记录数,最后用于分页
			String total = CountQuery.getSingleResult().toString();
			pageBean.setTotal(total);
			
			//查询展示数据
			Query pageQuery = session.createQuery(hql);
			//把值放进去
			this.setParamenter(pageQuery, map);
			pageQuery.setFirstResult(pageBean.getStartIndex());
			pageQuery.setMaxResults(pageBean.getRows());
			
			return pageQuery.list();
		}else {//不分页
			Query query = session.createQuery(hql);
			this.setParamenter(query, map);
			return query.list();
		}
		
		
	}
}

2.查询方法的调用

public List<Book> list2(Book book,PageBean pageBean){
		Session session = SessionFactoryUtils.getSession();
		Transaction transaction = session.beginTransaction();
		Map<String, Object> map = new HashMap<String, Object>();
		
		String hql = "from Book where 1=1";
		if(StringUtils.isNotBlank(book.getBookName())) {
			hql += " and bookName like :bookName ";
			map.put("bookName", book.getBookName());
		}
		
		List list = super.executeQuery(session, hql, pageBean, map);
		transaction.commit();
		session.close();
		
		
		return list;
	}

猜你喜欢

转载自blog.csdn.net/qq_40979551/article/details/83721526