setFirstResult和setMaxResult不适用于Order By [英] setFirstResult and setMaxResult doesn't work well with Order By

查看:218
本文介绍了setFirstResult和setMaxResult不适用于Order By的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么可能导致CriteriaQuery orderBy方法停止工作?

以下是实现:

    OpenJPAEntityManager kem = OpenJPAPersistence.cast(entityManager());
    kem.getFetchPlan().clearFetchGroups();
    kem.getFetchPlan().addFetchGroup("order_search");

    CriteriaBuilder builder = kem.getCriteriaBuilder();
    CriteriaQuery<Order> query = builder.createQuery(Order.class);
    Root<Order> order = query.from(Order.class);
    query.select(order);

    Predicate main_condition = buildWhereClause(builder, query, order, target_states, orderDate_from, orderDate_to, dueDate_from, dueDate_to, username);

    query.where(main_condition);

    query.orderBy(builder.desc(order.get("orderDate")));

    TypedQuery<Order> q = entityManager().createQuery(query);

    if (firstResult != 0)
        q.setFirstResult(firstResult);
    if (maxResults != 0)
        q.setMaxResults(maxResults);

以分页显示,当有15条记录并且我们希望每页5条记录时,它应该是:

-page1- 1 2 3 4 5 -page2- 6 7 8 9 10 -page3- 11 12 13 14 15

但是现在我们到这里了

-page1- 1 2 3 4 5 -page2- 6 7 8 9 10 -page3- 5 4 3 2 1

最后一页总是与第一页相反,为什么呢?

解决方案

将此

With the pagniation, when there are 15 records and we want 5 records per page, it should be:

-page1- 1 2 3 4 5 -page2- 6 7 8 9 10 -page3- 11 12 13 14 15

But now what we get here is

-page1- 1 2 3 4 5 -page2- 6 7 8 9 10 -page3- 5 4 3 2 1

the last page is always the opposite order of the first page, how come?

Nail it, not by myself, this post is quite helpful. I did the same and now it runs like a charm. Basically need to add the primary key in to the order by criteria otherwise the pagination just totally messed.

Spend 4 hours and the solution so simple and tricky. Works on OpenJPA 2.2.2 and Oracle 11g, I guess it is a constant trick since OpenJPA 1.2 from that post.

这篇关于setFirstResult和setMaxResult不适用于Order By的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆