Monday, October 31, 2005

Hibernate Pagination

Compatible with Hibernate 2.1.8, easily adaptable to 3.

Last rewritten on May, 2005, by Pietro Polsinelli.

I propose here a pagination solution, which took as starting point what can be found in hibernate team weblog. It is structured in an interface, Page, and two implementation classes:

* HibernatePage: uses the method suggested in the guide to feed the page. Has a (sample) factory method,

public static HibernatePage getHibernatePageInstance(Query query,
int page Number,
int pageSize,
String driverClass)

that in base of the driver class returns a HibernatePage that gets the total elements by scrolling, for databases that support scrollable resultsets: not many do it really (see below). For jdbc drivers that do not support scrollable resultsets, finally I just did query.list().size(). This can be optimized in particular instances; in general, a Hibernate user proposed "I was planning on converting the Hibernate query to SQL and then replacing the 'select .... from ...' with 'select count from ..' to get the real count'" but in order to make it work in all cases, you have to take into account that you may be returning arrays of objects, hence you have to modify the Hibernate query, which is not trivial. In fact I did some testing on Oracle 10 with driver 10, and the way it is done in the sample code, using query.list().size() resulted FASTER than the count(*) done in sql!

If you seriously consider performance, real problems are got by making wrong joins, forgetting to index columns and so on, where you may get multiplicative groth of required times. If anyway you are troubled by this, you can use proprietary sql tools (in particular in case of Oracle) to develop an OraclePage that avoids even that (assuming that Oracle will not release support for real scrollable resultsets): see the paragraph on Oracle below.

more...
code...
--
h.o.s.a.m.r.e.d
Be OpeN Mind
--
http://hosamred.blogspot.com

No comments: