1. 程式人生 > >Spring Hibernate 模板實現分頁

Spring Hibernate 模板實現分頁

public  List find( final  String hsql,  final int  firstRow,  final int  maxRow)  throws  Exception { 
  
return  getHibernateTemplate().executeFind( new
 HibernateCallback() { 
     public  Object doInHibernate(Session s)  throws
 HibernateException, SQLException { 
           Query query 
=
 s.createQuery(hsql); 
           query.setFirstResult(firstRow); 
           query.setMaxResults(maxRow); 
           List list 

=  query.list(); 
           return
 list; 
           } 
     }); 
}

Spring+hibernate 查詢物件總數

有兩種形式,一是HQL查詢,二是QBC查詢

 public int getPersonalcarCount(){
    int count=0;
       String sqls = "select count(*) as countRow from UsedPersonalcar u";
       SQLQuery query = getHibernateTemplate().getSessionFactory().getCurrentSession      ().createSQLQuery(sqls);
       query.addScalar("countRow", Hibernate.INTEGER);
       List topList = query.list();
       if (topList.get(0) != null)
          count = (Integer) topList.get(0);
       return count;

   }
  
   public int getPersonalcarCountByCriteria() {
     final DetachedCriteria detachedCriteria=DetachedCriteria.forClass(UsedPersonalcar.class);
  Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Criteria criteria = detachedCriteria.getExecutableCriteria(session);
    return criteria.setProjection(Projections.rowCount()).uniqueResult();
   }
  }, true);
  return count.intValue();
}