AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



java-hibernate: How to do pagination in Hibernate?

Could you forward the sample code.

java x 210
hibernate x 23
Posted On : 2017-02-02 15:11:44.0
profile MOHAMMAD SALEEM BASHA - anyforum.in MOHAMMAD SALEEM BASHA
266150
up-rate
4
down-rate

Answers


setFirstResult(int arg) & setMaxResults(int arg) mainly used for pagination. setFirstResult(int arg) is used to display the record from mentioned index as parameter and setMaxResults(int arg) is used to limit the records.

e.g.

Query query = this.getSession().createQuery("FROM Employee");
query.setFirstResult(0);
query.setMaxResults(20);
List employees= query.list();

If you are using a web application at bottom you display a list of links denoted by numbers based on the total valid records present in table divided by no of records you want to display on page. Initially in set First result you pass 0 and by clicking on each link displayed on the bottom of page you pass same number as parameter and get it in the class and set the starting index accordingly like below:

query.setFirstResult((page-1)*pagesize);

where page as parameter which you passed on the click of the link denoted by numbers and pagesize is the variable which is the total number of records you want to display on page.

There are some other techniques also to do the same thing like below:

HQL and the ScrollableResults API:
--------------------------------------------------------------------------------
String hql = "FROM Foo f order by f.name";
Query query = session.createQuery(hql);
int pageSize = 10;

ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
resultScroll.first();
resultScroll.scroll(0);
List<Foo> fooPage = Lists.newArrayList();
int i = 0;
while (pageSize > i++) {
fooPage.add((Foo) resultScroll.get(0));
if (!resultScroll.next())
break;
}
//Total count
resultScroll.last();
int totalResults = resultScroll.getRowNumber() + 1;


Simply the Criteria API:
-------------------------------------------------------
Criteria criteria = session.createCriteria(Foo.class);
criteria.setFirstResult(0);
criteria.setMaxResults(pageSize);
List<Foo> firstPage = criteria.list();
//Total count
Criteria criteriaCount = session.createCriteria(Foo.class);
criteriaCount.setProjection(Projections.rowCount());
Long count = (Long) criteriaCount.uniqueResult();

Posted On : 2017-02-04 11:22:24
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523185418912
Reply This Thread
up-rate
3
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in