//需要先行搭建好框架,创建好一个实体类Student及一个Util类pageBean
public class StudentDaoImpl implements IStudentDao {
@Override
public PageBean find(int pageIndex, int pageSize, String name,
Integer courseId, Integer stime, Integer educationId, Integer sstate) {
PageBean p=null;
//在打开数据库连接(session)之前先组装好查询条件
DetachedCriteria detCri=DetachedCriteria.forClass(Student.class);
//设置关联属性别名,执行内连接查询
detCri.createAlias("course", "c");
detCri.createAlias("education", "e");
//判断条件的有效性,组装条件
if(StringUtils.isNotEmpty(name)){
detCri.add(Restrictions.like("name",name,MatchMode.ANYWHERE));
}
if(courseId!=null){
detCri.add(Restrictions.eq("c.id",courseId));
}
if(stime!=null){
detCri.add(Restrictions.eq("stime",stime));
}
if(educationId!=null){
detCri.add(Restrictions.eq("e.id",educationId));
}
if(sstate!=null){
detCri.add(Restrictions.eq("sstate",sstate));
}
Session session=null;
try {
session=HibernateUtil.getSession();
//获得可执行的Criteria
Criteria criteria=detCri.getExecutableCriteria(session);
//设置聚合运算
criteria.setProjection(Projections.rowCount());
//查询总行数
int rowCount=((Number)criteria.uniqueResult()).intValue();
int pageCount=(rowCount%pageSize==0)?(rowCount/pageSize):(rowCount/pageSize+1);
int firstResult=(pageIndex-1)*pageSize;
criteria.setProjection(null);
List<Student> results=criteria.setFirstResult(firstResult)
.setMaxResults(pageSize)
.addOrder(Order.desc("id"))
.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE)
.list();
p.setPageIndex(pageIndex);
p.setPageSize(pageSize);
p.setRowCount(rowCount);
p.setPageCount(pageCount);
p.setResults(results);
} catch (Exception e) {
e.printStackTrace();
}
finally{
session.close();
}
return p;
}