/** * 使用HQL进行分页查询. * * @param hql 查询条件 * @param pageNo 页号,从1开始. * @param pageSize 每页中的记录数 * @param args HQL的参数 * @return 当前页的分页对象 */ public Page pagedQuery(String hql, int pageNo, int pageSize, Object... args) { Assert.hasText(hql); // 创建查询 Query query = getSession().createQuery(hql); // 根据华南提出的bug做出修正,做是否为null的判断 if (args != null) { for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } } String countQueryString = " SELECT count (*) " + removeSelect(removeOrders(hql)); List countlist = getHibernateTemplate().find(countQueryString, args); long totalCount = (Long) countlist.get(0); // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list; if (!entityQueryCache.isCached(hql, pageNo, pageSize, args)) { logger.debug("Not Using Cache for query: " + hql); list = query.setFirstResult(startIndex).setMaxResults(pageSize).list(); } else { logger.debug("Using Cache for query: " + hql); list = new ArrayList(); for (Iterator it = query.setFirstResult(startIndex).setMaxResults(pageSize).iterate(); it.hasNext(); ) { list.add(it.next()); } } return new Page(startIndex, totalCount, pageSize, list); }
/** * hql查询. * * @param hql 查寻条件 * @param values 可变参数 用户可以如下四种方式使用 dao.find(hql) dao.find(hql,arg0); dao.find(hql,arg0,arg1); * dao.find(hql,new Object[arg0,arg1,arg2]) * @return 符合条件的实体List */ public List find(String hql, Object... values) { if (!entityQueryCache.isCached(hql, values)) { logger.debug("Not Using Cache for query: " + hql); if (values.length == 0) return getHibernateTemplate().find(hql); else return getHibernateTemplate().find(hql, values); } else { logger.debug("Using Cache for query: " + hql); List list = new ArrayList(); if (values.length == 0) { for (Iterator it = getHibernateTemplate().iterate(hql); it.hasNext(); ) { list.add(it.next()); } } else { for (Iterator it = getHibernateTemplate().iterate(hql, values); it.hasNext(); ) { list.add(it.next()); } } return list; } }