0

In my application I need to get only 20 records among 200.Previously I was getting all records from database and initially showing only first 20 records in first page whenever user enter the page number or by clicking the navigation tabs user may get another 20 records.

But now I need to get only 20 records from database initially and also total count of records then only I can display the page numbers based on records total count. whenever user click on corresponding page number then only corresponding records will need to be displays which are fetched by hitting the database

I am new to hibernate that's why I am asking this question

Balaji Reddy
  • 5,576
  • 3
  • 36
  • 47
user3354457
  • 69
  • 2
  • 17

2 Answers2

4

Pagination can be achieved with the following two method of Query interface.

  query.setFirstResult(2);
  query.setMaxResults(4);

setFirstResult(int startingRecordsFrom): With the help of this method we can set the result in query which is starting from records.

setMaxResults(int maxRecords): With the help of this method we can set the maximum result in query.

Let say you have 100 records and you wish to retrieve only 10 records. your code should something like this

  final int pageSize =10;
  String hql = "FROM Employee";
  Query query = sess.createQuery(hql);
  query.setFirstResult(updatedStartIndex);
  query.setMaxResults(pageSize);
  List<Employee> employees = query.list();
  updatedStartIndex  =  updatedStartIndex +pageSize;

Here you have to maintain your updatedStartIndex variable somewhere in your program for next page request.

Hope this is helpful

Balaji Reddy
  • 5,576
  • 3
  • 36
  • 47
0
getHibernateTemplate().execute(new HibernateCallback<List<YourObject>>() {
    public List<YourObject> doInHibernate(Session session) throws HibernateException, SQLException {
        return session.createCriteria(YourObject.class).setMaxResults(resultsPerPage).setFirstResult(offset).list();
    }
});

You need a count also to see how many records do you have. Divide that count to the resultPerPage and you get the number of pages. The offset will be the currentPage * resultPerPage - resultPerPage;

Emil L
  • 20,219
  • 3
  • 44
  • 65
sergiu
  • 389
  • 1
  • 7