1

I have an Entity with a List<EntityRevision> contained in it. The collection has an @OrderColumn.

I'd like to get all the EntityRevisions for an Entity ordered by their index.

I can do this with the following query:

SELECT er 
  FROM Entity e JOIN e.revisions er 
  WHERE e.id = :entityId 
  ORDER BY index(er)

But I can't figure out how to do this with the CriteriaQuery.

Using EclipseLink 2.3.2 / JPA 2.0.3 - the Root<EntityRevision> has no index() method on it that I can use in the orderBy.

Any ideas?

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
Brian Repko
  • 326
  • 2
  • 9

2 Answers2

0

This worked for me:

final EntityManager m = ...
final CriteriaBuilder b = m.getCriteriaBuilder();
final CriteriaQuery<Child> q = b.createQuery( Child.class );
final Root<Parent> p = q.from( Parent.class );
final ListJoin<Parent, Child> j = p.join( Parent_.children );
final CriteriaQuery<Child> s = q.select( j );

s.where( b.equal( j.get( Child_.parent ), parent ) );
s.orderBy( b.asc( j.index() ) );

final TypedQuery<Child> t = m.createQuery( s );
final List<Child> children = t.getResultList();

Assert.assertEquals( parent.getChildren().size(), children.size() );
Assert.assertEquals( parent.getChildren(), children );
PA314159
  • 106
  • 1
  • 6
0

I have not tested it, but something like criteriaQuery.orderBy(criteriaBuilder.asc( ((ListJoin)root.get("listMapping")).index())); should work if your listMapping is a list with an orderby column.

Chris
  • 20,138
  • 2
  • 29
  • 43