问题描述
什么可能导致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
最后一页总是与第一页相反,为什么呢?
将此帖子非常有用.我做了同样的事情,现在它就像一个魅力.基本上需要按条件将主键添加到订单中,否则分页将完全混乱.
花费4个小时,解决方案是如此简单而棘手.在OpenJPA 2.2.2和Oracle 11g上都可以使用,我猜这是从该帖子开始的OpenJPA 1.2以来的一个恒定技巧.
What could cause the CriteriaQuery
orderBy
method stop working?
Here are the implementations:
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);
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!