Hibernate的QBC一定能满足你的需要~
这里给你个例子:
//B2C商城中根据商品标题模糊查询商品
public List findByTitle(String title, int pageIndex, int orderType) {
try {
Criteria criteria = this.currentSession().createCriteria(Goods.class);
// 是否只显示已发布商品
if (this.onlyShowEnabled) {
criteria.add(Restrictions.eq("enabled", true));
}
// 根据商品标题模糊查询
criteria.add(Restrictions.like("title", "%" + title + "%"));
// 选择排序方式
criteria = this.order(criteria, orderType);
// 分页处理
List list = super.page(criteria, pageIndex);
return list;
} catch(Exception e) {
System.out.println("GoodsDao >> findByTitle >> " + e);
return null;
}
}
//不同的排序方式
private Criteria order(Criteria criteria, int orderType) throws Exception {
if (orderType == IGoodsDao.ORDER_TYPE_LATEST) {
return criteria.addOrder(org.hibernate.criterion.Order.desc("publishDate"));
} else if (orderType == IGoodsDao.ORDER_TYPE_PRICE_HIGHEST) {
return criteria.addOrder(org.hibernate.criterion.Order.desc("maxPrice"));
} else if (orderType == IGoodsDao.ORDER_TYPE_PRICE_LOWEST) {
return criteria.addOrder(org.hibernate.criterion.Order.asc("minPrice"));
} else if (orderType == IGoodsDao.ORDER_TYPE_HOTTEST) {
return criteria.addOrder(org.hibernate.criterion.Order.desc("purchaseOrderNum"));
} else {
throw new Exception("不支持该排序类型");
}
}
至于super.page()方法是继承了一个BaseDao类,以下是实现:
/**
* QBC形式分页查询
* @param criteria 查询条件对象
* @param pageIndex 页码
* @param pageSize 页面大小
* @return 分页查询的结果
* @throws HibernateException
*/
protected List page(Criteria criteria, int pageIndex, int pageSize) throws HibernateException {
@SuppressWarnings("unchecked")
List list = criteria.setFirstResult(pageSize * pageIndex)
.setMaxResults(pageSize).list();
return list;
}