hql进阶

sql是可以写出通用查询且带分页的方法的,hql可以吗?答案是:可以的。

在这里把hql的通用查询方法的代码贴出来供大家参考。

这里直接上代码了,导依赖以及hibernate的配置就不贴了:

BaseDao.java

package com.crm.util;

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

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

public class BaseDao {	
	/**
	 * hibernate的通用查询
	 * @param hql hql语句
	 * @param param	参数集合,map中的key必须与hql语句中命名参数的名字所对应
	 * @param pageBean	分页
	 * @return
	 */
	public List executeQuery(Session session, String hql, Map<String, Object> param, PageBean pageBean){
		Query query = null;
                // 分页是需要查询数据总条数的
		if(pageBean!=null && pageBean.isPage()) {
			String countHql = this.getCountHql(hql);
			query = session.createQuery(countHql);
			this.setParameter(param, query);
			Long total = (Long) query.getSingleResult();
			pageBean.setTotal(total.toString());
		}
		query = session.createQuery(hql);
                //设置参数
		this.setParameter(param, query);
                //设置分页的页数以及每页的条数
		if(pageBean!=null && pageBean.isPage()) {
			query.setFirstResult((pageBean.getPage()-1)*pageBean.getRows());
			query.setMaxResults(pageBean.getRows());
		}
		return query.list();
	}
	
	/**
	 * 需求:根据传入的hql语句,得到获取数据总条数的hql语句
	 * 
	 * 传过来的hql会有两种情况:
00000	 * 	1、from 开头的
	 * 	2、select 开头的
	 * @param hql
	 * @return
	 */
	private String getCountHql(String hql) {
		int indexOf = hql.toUpperCase().indexOf("FROM");
                //截取form后面的代码,在前面拼接上select count(*)
		String hqlCover="select count(*) "+hql.substring(indexOf);
		return hqlCover;
	}
	/**
	 * 给命名参数赋值
	 * @param param
	 * @param query
	 * @return
	 */
	private void setParameter(Map<String, Object> param, Query query) {
                //如果没有参数则不赋值
		if(param == null || param.size()==0) return;
		String key=null;
		String value=null;
		for (Entry<String, Object> entry : param.entrySet()) {
			key = entry.getKey();
			value = entry.getValue();
			if(value instanceof Collection){
                            query.setParameterList(key, (Collection)value);
                        }else if(value instanceof Object[]){
                            query.setParameterList(key, (Object[])value);
                        }else{
                            query.setParameter(key, value);
			}
		}
	}
}

PageBean.java

package com.crm.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean {

	private int page = 1;// 页码
	private int rows = 10;// 行数/页大小
	private int total = 0;// 总记录数

	private boolean pagination = true;// 默认分页

	private String url;// 上一次请求的地址
	private Map<String, String[]> parameterMap;// 上一次请求的所有参数

	public PageBean() {
		super();
	}

	/**
	 * 对分页bean进行初始化
	 * 
	 * @param request
	 */
	public void setRequest(HttpServletRequest request) {
		// 公共参数
		this.setPage(request.getParameter("page"));
		this.setRows(request.getParameter("rows"));
		this.setPagination(request.getParameter("pagination"));

		// 请求地址和请求参数
		this.setUrl(request.getContextPath() + request.getServletPath());
		this.setParameterMap(request.getParameterMap());
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map<String, String[]> parameterMap) {
		this.parameterMap = parameterMap;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setPage(String page) {
		if (null != page && !"".equals(page.trim())) {
			this.page = Integer.parseInt(page);
		}
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setRows(String rows) {
		if (null != rows && !"".equals(rows.trim())) {
			this.rows = Integer.parseInt(rows);
		}
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPage() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public void setPagination(String pagination) {
		if ("false".equals(pagination)) {
			this.pagination = false;
		}
	}

	/**
	 * 下一页
	 * 
	 * @return
	 */
	public int getNextPage() {
		int nextPage = page + 1;
		if (nextPage > this.getMaxPage()) {
			nextPage = this.getMaxPage();
		}
		return nextPage;
	}

	/**
	 * 上一页
	 * 
	 * @return
	 */
	public int getPreviousPage() {
		int previousPage = page - 1;
		if (previousPage < 1) {
			previousPage = 1;
		}
		return previousPage;
	}

	/**
	 * 最大页码
	 * 
	 * @return
	 */
	public int getMaxPage() {
		return total % rows == 0 ? total / rows : total / rows + 1;
	}

	/**
	 * 起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (page - 1) * rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

 

hibernate中原生sql的使用:

package com.hibernate.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;

import com.hibernate.util.HibernateUtils;
public class Test {
	
	public static void main(String[] args) {
		Session session = HibernateUtils.getSession();
		Transaction beginTransaction = session.beginTransaction();
             // 原生sql
                String sql="select * from t_hibernate_book";
            //    使用hql调用的是    createQuery()方法
            //    使用sql调用的是    createSQLQuery()方法
		NativeQuery query = session.createSQLQuery(sql);  
                List list= query.list();
		list.stream().forEach(a -> System.out.println(Arrays.toString((Object[])a)));
		beginTransaction.commit();
		session.close();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值