Hibernate
hibernate实现limit效果
- 由于hql语句内无法直接书写limit语法,所以需要通过别的方式来达成这个效果
- limit效果一般需要有两个参数:开始位置start和查询数量num。两个参数都是final int型
- 实现代码如下:
try {
//首先新建一个final型的hql语句
final String hql="from xxb where xx="+xx+" order by xx asc ";
//hibernate执行查找,参数为请求返回方法
List<xx> xxList=getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session){
//创建查找对象 ,设置起始位置以及查询数量
Query query=session.createQuery(hql);
query.setFirstResult(start);
query.setMaxResults(num);
//转换为list形式
return query.list();
}
});
return xxList;
}catch (RuntimeException e){
throw e;
}
- 对于实现过程中的两个相关方法,截取其源码贴在下方,也可以自行查看。
public List executeFind(HibernateCallback<?> action) throws DataAccessException {
Object result = this.doExecute(action, false, false);
if (result != null && !(result instanceof List)) {
throw new InvalidDataAccessApiUsageException("Result object returned from HibernateCallback isn't a List: [" + result + "]");
} else {
return (List)result;
}
}
public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery(this.hql).setFirstResult(this.pageModel.getBeginIndex()).setMaxResults(this.pageModel.getPageSize());
if (!CollectionUtil.listIsNull(this.params)) {
for(int i = 0; i < this.params.size(); ++i) {
Object obj = this.params.get(i);
if (obj instanceof String) {
query.setString(i, (String)obj);
} else if (obj instanceof Integer) {
query.setInteger(i, (Integer)obj);
} else if (obj instanceof Date) {
query.setDate(i, (Date)obj);
}
}
}
List<T> list = query.list();
String counthql = "select count(*) " + this.hql;
Query countQuery = session.createQuery(counthql);
if (!CollectionUtil.listIsNull(this.params)) {
for(int i = 0; i < this.params.size(); ++i) {
Object obj = this.params.get(i);
if (obj instanceof String) {
countQuery.setString(i, (String)obj);
} else if (obj instanceof Integer) {
countQuery.setInteger(i, (Integer)obj);
} else if (obj instanceof Date) {
countQuery.setDate(i, (Date)obj);
}
}
}
List<Object> countList = countQuery.list();
if (CollectionUtil.listIsNull(countList)) {
this.pageModel.setTotalCount(0L);
} else {
this.pageModel.setTotalCount((Long)countList.get(0));
}
return list;
}