package com.google.util; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /** * 定义一个处理分页查询的类 * @author Administrator * */ public class PageObject { private int totalRecord = 0;//总记录数 private int pageSize = 10;//一页显示的条数 private int currentPage = 1;//当前页 private int totalPage = 1;//总页数 private String hql; //执行查询的语句 private ArrayList params; //hql参数 private List result; //返回结果集 //创建构造器 public PageObject(){ } /** * 固定类的分页 from ClassPO * @param hql 查询语句 * @param param 查询参数 * @param pageSize 每页的条数 * @param currentPage 当前页 */ public PageObject(String hql, ArrayList params, int pageSize, int currentPage){ if(currentPage <=0 ){ this.currentPage = 1; }else{ this.currentPage = currentPage; } if(pageSize <= 0){ this.pageSize = 10; }else{ this.pageSize = pageSize; } this.hql = hql; this.params = params; getCount(); result(); } public int getTotalRecord() { return totalRecord; } public int getPageSize() { return pageSize; } public int getCurrentPage() { return currentPage; } public int getTotalPage() { return totalPage; } public ArrayList getParams() { return params; } public void setParams(ArrayList params) { this.params = params; } public List getResult() { return result; } public void setResult(List result) { this.result = result; } /** * 获取条数信息 */ public void getCount(){ Session session = null; List list = null; try { session = HibernateUtil.openSession(); if(session == null){ System.out.println("--------------------------"); } String str = new String(); str = "select count(*) "; //判断hql是不是select or SELECT开始的 if(hql.toLowerCase().trim().indexOf("select") == 0){ //如果是select 语句开始的,则在str中添加select count(*) from( hql ) //获取from开始的字串 str += hql.substring(hql.toLowerCase().indexOf("from")); System.out.println("是select 开始的hql "+ str); }else{ //如果是一个PO from CPO,则只是添加select count(*) 即可 str += hql; System.out.println("不是select 开始的hql "+ str); } System.out.println("====================="+str); Query query = session.createQuery(str); query = addParams(query, params); //设置总记录数 totalRecord = Integer.parseInt(query.uniqueResult().toString()); // this.setTotalRecord(Integer.parseInt(query.uniqueResult().toString())); //设置总页数 totalPage = (totalRecord-1)/pageSize+1; // this.setTotalPage((totalRecord-1)/pageSize+1); } catch (Exception e) { throw new RuntimeException("设置页面信息:"+e.getMessage()); }finally{ if(session != null && session.isOpen()){ session.close(); } } } //执行查询 public void result(){ Session session = null; Transaction tx = null; List list = null; try { session = HibernateUtil.getCurrentSession(); tx = session.beginTransaction(); System.out.println(this.hql); Query query = session.createQuery(this.hql); String str = "select count(*) from ("; str += this.hql; str += ")"; query = addParams(query, params); list = query.setFirstResult((currentPage-1)*pageSize).setMaxResults(pageSize).list(); this.setResult(list); tx.commit(); } catch (Exception e) { if(tx!=null){ tx.rollback(); } e.printStackTrace(); throw new RuntimeException("----"+e.getMessage()); }finally{ if(session != null && session.isOpen()){ session.close(); } } } public Query addParams(Query query, ArrayList params){ //添加参数到hql if(params!=null && params.size() >0){ for(int i=0; i < params.size(); i++){ query.setParameter(i, params.get(i)); } } return query; } }
//附带HibernateUtil.java
package com.google.util; //import org.hibernate.Session; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; final public class HibernateUtil { private static SessionFactory sessionFactory = null; private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); public HibernateUtil(){ } static{ sessionFactory = new Configuration().configure().buildSessionFactory(); } //获取全新的session public static Session openSession(){ return sessionFactory.openSession(); } //获取和线程关联的session public static Session getCurrentSession(){ Session session = threadLocal.get(); //判断是否得到 //add by yyy || !session.isOpen() if(session == null || !session.isOpen()){ session = sessionFactory.openSession(); //session对象设置到threadLocal -- 相当于session和线程绑定 threadLocal.set(session); } return session; } /** * 查询方法 */ public static List executeQuery1(String hql, String[] parameters){ Session session = null; List list = null; try { session = openSession(); Query query = session.createQuery(hql); if(parameters != null && parameters.length > 0){ for(int i=0; i< parameters.length; i++){ query.setParameter(i, parameters[i]); } } list = query.list(); } catch (Exception e) { e.getStackTrace(); throw new RuntimeException(e.getMessage()); }finally{ if(session != null && session.isOpen()){ session.close(); } } return list; } /** * 同意的查询方法:参数使用ArrayList */ public static List executeQuery(String hql, ArrayList al){ Session session = null; List list = null; try { session = openSession(); Query query = session.createQuery(hql); //注入参数 if(al!=null && al.size() > 0){ for(int i=0; i < al.size(); i++){ query.setParameter(i, al.get(i)); } System.out.println(al.toString()); } //执行查询 list = query.list(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Util executeQuery"+e.getMessage()); }finally{ if(session != null && session.isOpen()){ session.close(); } } return list; } /** * 同意的分页查询方法 没有确定的PO */ public static Map executeQueryByPage(String hql, ArrayList parameter, int pageSize, int currentPage){ Session session = null; int pageCount = 1;//总页数 int totalCount = 0;//总记录数 //pageSize一页显示的条数 //currentPage 当前页 List<Object[]> result = null; HashMap map = new HashMap(); try { session = openSession(); Query query = session.createQuery(hql); if(parameter != null && parameter.size() > 0){ for(int i=0; i< parameter.size(); i++){ query.setParameter(i, parameter.get(i)); } } //获取总记录数 totalCount = query.list().size(); System.out.println(totalCount); //计算总页数 if(totalCount >=1){ pageCount = (totalCount-1)/pageSize+1; } //先测试分页情况 /* for(int i=1; i<=pageCount; i++){ // System.out.println("------------第"+i+"页----------------"); result = query.setFirstResult((i-1)*pageSize).setMaxResults(i*pageSize).list(); }*/ /*if(result.size()>0){ for(int k = 0; k < result.size(); k++){ Object[] obj = result.get(k); for(int j=0; j< obj.length; j++){ System.out.print(obj[j].toString()+" "); } System.out.println(); } }*/ result = query.setFirstResult((currentPage-1)*pageSize).setMaxResults(pageSize).list(); map.put("TOTAL_COUNT", totalCount); map.put("RESULT", result); map.put("PAGE_COUNT", pageCount); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return map; } }