怎么使用HibernateTemplate实现分页并且有条件查询
如何使用HibernateTemplate实现分页并且有条件查询
这是我的代码,目的是想通过Topic查询topic下的Reply这样虽然实现了分页,可是无法按Topic 条件查询了,
不知道有没有别的方法既可以实现分页,又能够添加条件约束
public List <Reply> query(Topic topic, final int begin, final int max) {
final String sql= "from Reply ";
List <Reply> replies=(List <Reply> )hibernateTemplate.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,SQLException {
List <?> list=session.createQuery(sql).setFirstResult(begin).setMaxResults(max).list();
return list;
}
});
return replies;
}
------解决方案--------------------
这是我的代码,目的是想通过Topic查询topic下的Reply这样虽然实现了分页,可是无法按Topic 条件查询了,
不知道有没有别的方法既可以实现分页,又能够添加条件约束
public List <Reply> query(Topic topic, final int begin, final int max) {
final String sql= "from Reply ";
List <Reply> replies=(List <Reply> )hibernateTemplate.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,SQLException {
List <?> list=session.createQuery(sql).setFirstResult(begin).setMaxResults(max).list();
return list;
}
});
return replies;
}
------解决方案--------------------
- Java code
/** * <li>QBC查询</li> * * @author 旦旦而学 * @param c:查询的类 * @param obj:查询的对象 * @param orber:按那几个字段排序 * @param row:每页显示多少行 * @param pages:当前显示第几页,从1开始 * @exception HibernateException * @return List */ public <T> List<T> find(Class<T> c, T obj, String[] orders, int row, int pages) throws HibernateException { Criteria criteria = this.getSession().createCriteria(c); if (obj != null) { Example example = Example.create(obj); example.enableLike(MatchMode.ANYWHERE);// 匹配模式,使用模糊查询必填项。 example.excludeNone();// 空的不做查询条件 example.excludeZeroes();// 0不要查询 example.ignoreCase(); // 不区分大小写 criteria.add(example); } if (row > 0 && pages > 0) { criteria.setMaxResults(row);// 最大显示记录数 criteria.setFirstResult((pages - 1) * row);// 从第几条开始 } // 判断是否有排序请求,如果有加入到排序方法中 if (orders != null) { for (int i = 0; i < orders.length; i++) criteria.addOrder(Order.desc(orders[i])); } return criteria.list(); }
------解决方案--------------------
sql= "from Reply r where r.topic.id="+topic.getId();
------解决方案--------------------
session.createQuery(sql).setFirstResult(begin).setMaxResults(max).list();
在这个查询之上要根据topic中的chaxun条件重新拼接sql,如:
sql+“ WHERE NAME=”+topic.getName
然后将拼接的sql放到Query里面去