刚好遇见了
- hibernate 中 hql 不能写分页语句如(mysql的limit);
- hibernateTemplate 中仅有setMaxResults()设置查询条数,而没有setFirstResult() 设置开始位置时
- 但是我需要分页,我该怎么办?
恰好看见了
- 可以使用 session中的createQuery语句
- 通过createQuery().setFirstResult().setMaxResult()来设置分页
菜单摆好了
Collection<T> collections = (Collection<T>) this.hibernateTemplate.execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Collection<T> collection = (Collection<T>) session.createQuery(stringBuffer.toString()).setFirstResult(Integer.parseInt(limit)).setMaxResults(Integer.parseInt(offset)).list()
return collection
}
})
开始吃了
@Override
public Collection<T> queryEntryByCondition(Map<String, Object> mapCondition,final String limit,final String offset) {
final StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("from "+this.entityClass.getName());
Set<String> set = mapCondition.keySet();
boolean isStart = false;
int i = 0;
for (String key:set){
i++;
if(isStart == false){
stringBuffer.append(" where ");
isStart = true;
}
if(i == set.size()){
stringBuffer.append(key+mapCondition.get(key));
}else{
stringBuffer.append(key+mapCondition.get(key) +" and ");
}
}
stringBuffer.append(" order by create_time desc ");
if(limit != null && limit != "" && offset != null && offset != "") {
Collection<T> collections = (Collection<T>) this.hibernateTemplate.execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Collection<T> collection = (Collection<T>) session.createQuery(stringBuffer.toString()).setFirstResult(Integer.parseInt(limit)).setMaxResults(Integer.parseInt(offset)).list();
return collection;
}
});
return collections;
}else{
return (Collection<T>) this.hibernateTemplate.find(stringBuffer.toString());
}
}