1、通过getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria()创建criteria对象
2、criteria通过add方法将expression封装起来,criteria是接口,simpleExpression实现了该接口
3、criteria.list()方法,找到符合条件的结果
4、setFirstResult()、setMaxResults()设置开始记录和最大记录数
public List<Product> products(String name, String shortString,
String itemNo, String categoryId, String subcategoryId,
Integer offset, Integer length) throws Exception {
Criteria criteria = openSession().createCriteria(Product.class);
Criterion ors = null;
if ((name != null) && (!"".equals(name.trim()))) {
ors = Restrictions.like("name", name, MatchMode.ANYWHERE);
}
if ((shortString != null) && (!"".equals(shortString.trim()))) {
if(ors == null)
ors = Restrictions.like("shortString", shortString, MatchMode.ANYWHERE);
else
ors = Restrictions.or(ors, Restrictions.like("shortString", shortString, MatchMode.ANYWHERE));
}
if ((itemNo != null) && (!"".equals(itemNo.trim()))) {
if(ors == null)
ors = Restrictions.like("itemNo", itemNo, MatchMode.ANYWHERE);
else
ors = Restrictions.or(ors, Restrictions.like("itemNo", itemNo, MatchMode.ANYWHERE));
}
if(ors != null)
criteria.add(ors);
if ((categoryId != null) && (!"".equals(categoryId.trim()))) {
criteria.add(Restrictions.eq("categoryId", categoryId));
}
if ((subcategoryId != null) && (!"".equals(subcategoryId.trim()))) {
criteria.add(Restrictions.eq("subcategoryId", subcategoryId));
}
if (offset != null) {
// 从第几条开始
criteria.setFirstResult(offset.intValue());
}
if (length != null) {
// 最大显示记录数
criteria.setMaxResults(length.intValue());
}
return criteria.list();
}