1. 程式人生 > >HQL的通用分頁

HQL的通用分頁

PageBean:

package com.zking.hibernate.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分頁工具類
 *
 */
public class PageBean {

	private int page = 1;// 頁碼

	private int rows = 2;// 頁大小

	private int total = 0;// 總記錄數

	private boolean pagination = true;// 是否分頁
	// 獲取前臺向後臺提交的所有引數
	private Map<String, String[]> parameterMap;
	// 獲取上一次訪問後臺的url
	private String url;

	/**
	 * 初始化pagebean
	 * 
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		// 只有jsp頁面上填寫pagination=false才是不分頁
		this.setPagination(!"fasle".equals(req.getParameter("pagination")));
		this.setParameterMap(req.getParameterMap());
		this.setUrl(req.getRequestURL().toString());
	}

	public int getMaxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}

	public int nextPage() {
		return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
	}

	public int previousPage() {
		return this.page > 1 ? this.page - 1 : 1;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

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

	public void setPage(String page) {
		this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
	}

	public int getRows() {
		return rows;
	}

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

	public void setRows(String rows) {
		this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(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 isPagination() {
		return pagination;
	}

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

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

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

	public String getUrl() {
		return url;
	}

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

	/**
	 * 獲得起始記錄的下標
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

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

}

StringUtils:

package com.zking.hibernate.util;

public class StringUtils {
	// 私有的構造方法,保護此類不能在外部例項化
	private StringUtils() {
	}

	/**
	 * 如果字串等於null或去空格後等於"",則返回true,否則返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字串不等於null或去空格後不等於"",則返回true,否則返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

BaseDao:

package com.zking.hibernate.dao;

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;

import com.zking.hibernate.util.PageBean;

public class BaseDao {

	private void setparameter(Query query, Map<String, Object> map) {
		if (null == map || map.size() == 0) {
			return;
		}
		// 給query賦值
		Object value = null;
		for (Entry<String, Object> entry : map.entrySet()) {
			value = entry.getValue();// 賦值給value
			if (value instanceof Collection) {
				query.setParameterList(entry.getKey(), (java.util.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");// 擷取from後面的sql語句
		return "select count(*) " + hql.substring(index);// 查詢總數
	}

	public List executeQuery(String hql, PageBean pageBean, Session session, Map<String, Object> map) {
		if (null != pageBean && pageBean.isPagination()) {
			String countHql = getCountHql(hql);
			Query counQuery = session.createQuery(countHql);
			this.setparameter(counQuery, map);
			String total = counQuery.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();
		}
	}

}

Book實體類

package com.zking.hibernate.etity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Book implements Serializable {
	/**
	 */
	private static final long serialVersionUID = -3143423339101308878L;
	private Integer book_id;
	private String book_name;
	private Float book_price;
	private Set<Category> categorys = new HashSet<>();
	private Integer initcategorys;

	@Override
	public String toString() {
		return "Book [book_id="+ book_id +",book_name="+ book_name +",book_price="+ book_price +",categorys="+ categorys +"]";
	}

	public Integer getBook_id() {
		return book_id;
	}
	
	public void setBook_id(Integer book_id) {
		this.book_id = book_id;
	}

	public String getBook_name() {
		return book_name;
	}

	public void setBook_name(String book_name) {
		this.book_name = book_name;
	}

	public Float getBook_price() {
		return book_price;
	}

	public void setBook_price(Float book_price) {
		this.book_price = book_price;
	}

	public Set<Category> getCategorys() {
		return categorys;
	}

	public void setCategorys(Set<Category> categorys) {
		this.categorys = categorys;
	}

	public Book() {
		super();
	}

	public Integer getInitcategorys() {
		return initcategorys;
	}

	public void setInitcategorys(Integer initcategorys) {
		this.initcategorys = initcategorys;
	}
	
	public Book(Integer book_id, String book_name) {
		super();
		this.book_id = book_id;
		this.book_name = book_name;
	}

	public Book(Integer book_id,String book_name,Float book_price,Set<Category> categorys) {
		super();
		this.book_id = book_id;
		this.book_name = book_name;
		this.book_price = book_price;
		this.categorys = categorys;
	}
}

Book.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.zking.hibernate.etity.Book" table="t_hibernate_book">
		<id name="book_id" type="java.lang.Integer" column="book_id">
			<generator class="increment" />
		</id>
		<property name="book_name" type="java.lang.String" column="book_name"></property>
		<property name="book_price" type="java.lang.Float" column="price"></property>
	</class>
</hibernate-mapping>

BookDao:

package com.zking.hibernate.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.zking.hibernate.etity.Book;
import com.zking.hibernate.util.HibernateUtil;
import com.zking.hibernate.util.PageBean;
import com.zking.hibernate.util.StringUtils;

public class BookDao1 extends BaseDao{
	public List<Book> list1(Book book,PageBean  pageBean){
		Session session = HibernateUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Map<String, Object> map = new HashMap<>();
		StringBuffer hql = new StringBuffer("from Book where 1=1");//初始化程式碼
		if (StringUtils.isNotBlank(book.getBook_name())) {//名字不為空就拼接hql語句
			hql.append(" and book_name like :bookname");
			map.put("bookname", "%"+book.getBook_name()+"%");
		}
//		super.executeQuery(hql, pageBean, session, map);
//		return list;
		return null;
	}
	
	public List<Book> list2(Book book,PageBean  pageBean){
		Session session = HibernateUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Map<String, Object> map = new HashMap<>();
		String hql = "from Book where 1=1";//初始化程式碼
		if (StringUtils.isNotBlank(book.getBook_name())) {//名字不為空就拼接hql語句
			hql+=" and book_name like :bookname";
			map.put("bookname", "%"+book.getBook_name()+"%");
		}
		List list = super.executeQuery(hql, pageBean, session, map);
		return list;
	}

}

BoodTest測試類:

package com.zking.hibernate.test;

import java.util.List;

import org.junit.Test;

import com.zking.hibernate.dao.BookDao1;
import com.zking.hibernate.etity.Book;
import com.zking.hibernate.util.PageBean;

public class BookLike {
	
	private BookDao1  bookDao = new BookDao1();
	
	@Test
	public void run1() {
		Book  book = new Book();
//		book.setBook_name("西");
		PageBean  pageBean = new PageBean();
		List<Book> list1 = this.bookDao.list2(book, pageBean);
		for(Book b : list1) {
			System.out.println(b);
		}
	}

}