Java Mailing List Archive

Home » users.openjpa »

Ordering results obtained through query-by-example

Miguel Muñoz


Replies: Find Java Web Hosting

Author LoginPost Reply

I'm using the OpenJPA query-by-example API, and it works fine unless I order my results. When I do that, I get way too many results. If I search without specifying an order, I get 4 results from a table of 9 rows. If I specify an order, I get 36 results instead. (I get everything four times.) The number I get is always the number I'm supposed to get multiplied by the number of rows.

Has anybody else seen this behavior? I'm trying to figure out if I'm doing something wrong, or if it's a bug in the JPA code.

Here's my method, if you're interested:

 private final Class<E> persistentClass;

 public List<E> findByExample(
     @NotNull E exampleInstance,
     @Nullable Attribute<E,?>[] excludeProperty,
     SingularAttribute<E,?>… orderFields
 ) throws DAORuntimeException {
   EntityManager entityManager = JpaUtil.getEntityManager();
   OpenJPACriteriaBuilder builder = (OpenJPACriteriaBuilder) entityManager.getCriteriaBuilder();
   CriteriaQuery<E> qDef = builder.createQuery(persistentClass);
   Root<E> from = qDef.from(persistentClass);;
   qDef.where(builder.qbe(from, exampleInstance, excludeProperty)); // query by example
   Query query = entityManager.createQuery(qDef);

   List<Order> orderList = makeOrderList(builder, qDef.from(persistentClass), orderFields);
   if (!orderList.isEmpty()) {

   return (List<E>) query.getResultList();

 private List<Order> makeOrderList(
     CriteriaBuilder builder,
     Root<E> root,
     SingularAttribute<E, ?>[] pOrderFields
 ) {
   List<Order> orderList = new LinkedList<>();
   for (SingularAttribute<E, ?> attribute: pOrderFields) {
   return orderList;

If I call it like this, it works fine:

   List<Incident> dIncidentList = incidentDao.findByExample(dExample, null);

If I call it like this, it returns lots of duplicates:

   List<Incident> dIncidentList = incidentDao.findByExample(dExample, null, Incident_.entryTime);

Is it me? Has anyone else seen this bug?


Miguel Muñoz


The Sun, with all those planets revolving around it and dependent on it, can still ripen a vine of grapes like it had nothing else to do in the world.

-- Galileo


There are seven sins in the world.
  Wealth without work.
  Pleasure without conscience.
  Knowledge without character.
  Commerce without morality.
  Science without humanity.
  Worship without sacrifice.
  Politics without principle.

-- Mohandas Gandhi


If tyranny and oppression come to this land, it will come in the guise of fighting a foreign enemy.

-- James Madison

©2008 - Jax Systems, LLC, U.S.A.