setFirstResult and setMaxResults doesnt work as expected

cz_Nesh picture cz_Nesh · Feb 22, 2013 · Viewed 18.9k times · Source

I have a problem with paging in my application. I wanna use setFirstResult and setMaxResults methods, but it gave me wrong output:

(My database: SQLite)

Example:

    Session session = HibernateUtil.getSessionFactory().openSession();

    int page = 0;
    int maxRows = 20;

    while (page < 5) {

        Criteria criteria = session.createCriteria(Book.class);
        criteria.setFirstResult(page * maxRows).setMaxResults(maxRows);
        criteria.addOrder(Order.asc("id"));
        List<Book> list = criteria.list();

        System.out.println("FirstRow: " + page * maxRows + " - RowsLimit: " + maxRows);
        for (Book b : list) {
            System.out.println(b.getId());
        }
        page++;
    }
    session.close();

The output gave me:

FirstRow: 0 - RowsLimit: 20
1
.
.
.
20
FirstRow: 20 - RowsLimit: 20
21
.
.
.
40
FirstRow: 40 - RowsLimit: 20
21
.
.
.
40
FirstRow: 60 - RowsLimit: 20
21
.
.
.
40

I have no idea why only first two "pages" are working correctly and after them it gave me the same range of rows.

Thx for any advice

Answer

cz_Nesh picture cz_Nesh · Feb 23, 2013

Ok here is the solution.

http://shagy0101.blogspot.cz/2012/03/sqlite-jpa-hibernate-pagination.html

Problem was in SQLite Dialect. Just add to your SQLiteDialect this method:

 @Override
 public boolean bindLimitParametersInReverseOrder(){
     return true;
 }