一个通用分页查询方法

时间:2021-09-04 12:59:13
/** 
* HQL分页查询,可以指定具体的模式,
* 采用getCount方式,须在此层完成hsql的转换与查询。
* 注意参数Object...args的应用,可以在查询的设置查询条件用的(JDK5.0语法)
*/
public Page pagedQuery(String hql, int pageNo, int pageSize, Object... args) {
Assert.hasText(hql);
Query query = getSession().createQuery(hql);
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);
int totalCount = (Integer) countlist.get(0);
return HqlPage.getPageInstanceByCount(query, pageNo, pageSize, totalCount);
}

/**
* 去除select 子句,未考虑union的情况
*/
private static String removeSelect(String hql) {
Assert.hasText(hql);
int beginPos = hql.toLowerCase().indexOf("from");
Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'");
return hql.substring(beginPos);
}

/**
* 去除orderby 子句
*/
private static String removeOrders(String hql) {
Assert.hasText(hql);
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(hql);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
}
m.appendTail(sb);
return sb.toString();
}