java setFirstResult 和 setMaxResults 没有按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15028043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:16:25  来源:igfitidea点击:

setFirstResult and setMaxResults doesnt work as expected

javahibernatesqlitedialect

提问by cz_Nesh

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

我的应用程序中的分页有问题。我想使用 setFirstResult 和 setMaxResults 方法,但它给了我错误的输出:

(My database: SQLite)

(我的数据库: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

感谢任何建议

回答by cz_Nesh

Ok here is the solution.

好的,这是解决方案。

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

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

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

问题出在 SQLite 方言中。只需将此方法添加到您的 SQLiteDialect 中:

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