前几天做项目的时候,用到了Creiteria来查询和分页。实在好用。但本人愚笨,用了不少时间,今天有空把用法记录下来,备忘。
多条件循环查询:
String comId = param.getCompany().getId();
List<TDepartment> depts = param.getDepartments();
String name = param.getName() + "";
String phoneNum = param.getPhoneNum() + "";
Criteria criteria = getIBaseDAO().getCurrentSession().createCriteria(TCompanyDirectory.class);
if (depts != null) {
Disjunction dis = Restrictions.disjunction();//多条件查询准备
for (TDepartment dept : depts) { //查询所有外键部门Id符合条件的员工
dis.add(Restrictions.eq("department.id", "" + dept.getId()));
}
criteria.add(dis);
}
criteria.add(Restrictions.eq("company.id", comId));
criteria.add(Restrictions.like("name", "%" + name + "%"));
criteria.add(Restrictions.like("mobilePhone", "%" + phoneNum + "%"));
criteria.addOrder(Order.asc("name"));
分页
criteria.setProjection(null);
SearchCompanyDirectoryResult searchResult = new SearchCompanyDirectoryResult();
searchResult.setTotalCount(criteria.list().size());
criteria.setFirstResult(beginIndex);
criteria.setMaxResults(everyPage);
searchResult.setCds(criteria.list());
searchResult.setListDepts(param.getCompany().getDepartments());
return searchResult;