Paging display has always been a big problem in web development, traditional web design only in a JSP or ASP pages to write all the code on the operation of the database, so that the page may be easier, but when the site layered development, pagination is more difficult, the following is I do spring+ HIBERNATE+STRUTS2 project design of the paging code, and share the exchange.
1, the DAO layer interface design, in the Memberdao interface has defined the following two methods:
public interface MemberDao{
//省略了其他的代码
/** *//**
* 分页查询
* @param hql 查询的条件
* @param offset 开始记录
* @param length 一次查询几条记录
* @return
*/
public List queryForPage(final String hql,final int offset,final int length);
/** *//**
* 查询所有记录数
* @param hql 查询的条件
* @return 总记录数
*/
public int getAllRowCount(String hql);
}
2, the DAO Layer implementation class Memberdaoimpl the above two methods are implemented as follows:
public class Memberdaoimpl extends Hibernatedaosupport implements Memberdao {
//omitted other code
/* * *//**
* Paging Query
* @param hql query conditions
* @param offset start record
* @param length query several records at once
* @retu RN
*/
Public List queryforpage (final String hql,final int offset,final int length) {
List list = Get Hibernatetemplate (). Executefind (New Hibernatecallback () {
Public Object Doinhibernate (sessions session) throws Hi bernateexception,sqlexception{
Query query = session.createquery (HQL);
Query.setfirstresult (offset);
Query.setmaxresults (length);
List List = Query.list ();
return list;
}
});
return list;
}
/** *//**
* Query all records
* @return Total record number
*/
public int getallrowcount (String h QL) {
return gethibernatetemplate (). Find (HQL). Size ();
}
}
Attentive readers will find that this class inherits the Hibernatedaosupport class, Hibernatedaosupport is the class that spring provides for hibernate support, Gethibernatetemplate (). Executefind (New Hibernatecallback () {...}) method, we use the interface callback, in which we can invoke Query.setfirstresult (offset) and query.setmaxresults (length) like native hibernate to implement paging query.