hibernate 创建BaseDAO帮助类

  1. BaseDAO
    通过书籍名字模糊查询数据,并且具备分页的功能
  2. 原生sql
    hql实现不了的功能,比如当联表查询的关联表超过三张以上 可以考虑使用原生sql、视图、存储过程
package com.zking.util;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

/**
 * 分页:
 * 	jdbc:
 * 		1.SQL——>countSQL——>total——>pageBean
 * 		2.SQL——>pageSQL——>result
 * 		3.处理结果集
 * 	hibernate:
 * 		1.SQL——>countSQL——>total——>pageBean
 * 		2.SQL——>pageSQL——>result(hibernate调用内置接口,自动生成分页语句,查询结果)
 * 		3.不需要
 * @author Administrator
 *
 * 2018年10月30日下午4:36:03
 */
public class BaseDao {
	/**
	 * 给Query赋值 (内部调用)
	 * @param query
	 * @param map
	 * 2018年10月30日下午6:30:44
	 */
	private void setParamerter(Query<?> query, Map<String, Object> map) {
		if (map == null || map.size() == 0) {
			return ;
		}
		Object value = "";
		for (Entry<String, Object> entry : map.entrySet()) {
			value = entry.getValue();
			if (value instanceof Collection) {
				query.setParameter(entry.getKey(), (Collection) value);
			} else if (value instanceof Object[]) {
				query.setParameter(entry.getKey(), (Object[]) value);
			} else {
				query.setParameter(entry.getKey(), value);
			}
		}
	}
	/**
	 * 私有 内部调用 拼接计数SQL
	 * @param hql
	 * @return
	 * 2018年10月30日下午6:28:18
	 */
	private String getCountHql(String hql) {
		int index = hql.toUpperCase().indexOf("FROM");
		return "select count(*) " + hql.substring(index);
	}
	/**
	 * 外部调用类
	 * @param hql
	 * @param pageBean
	 * @param map
	 * @param session
	 * @return
	 * 2018年10月30日下午6:27:52
	 */
	public List<?> executeQuery(String hql, PageBean pageBean, Map<String, Object> map, Session session) {
		Query<?> query = null;
		if (pageBean != null && pageBean.isPagination()) {
			String countHql = getCountHql(hql);
			query = session.createQuery(countHql);
			this.setParamerter(query, map);
			String total = query.getSingleResult().toString();
			pageBean.setTotal(total);
			query = session.createQuery(hql);
			this.setParamerter(query, map);
			query.setFirstResult(pageBean.getStartIndex());
			query.setMaxResults(pageBean.getRows());
		} else {
			query = session.createQuery(hql);
			this.setParamerter(query, map);
		}
		return query.list();
	}
}

猜你喜欢

转载自blog.csdn.net/f_1314520/article/details/83546795