3

Let say I have a generic method using JPA to list out entities

    public <T> List<T> list(Class<T> entity) throws Exception {

        List<T> result = new ArrayList<T>();
        CriteriaBuilder builder = em.getCriteriaBuilder();

        CriteriaQuery<T> query = builder.createQuery( entity );
        Root<T> root = query.from( entity );

        query.select( root );

        //possible?
        query.orderBy(builder.asc(...));

        result = em.createQuery( query ).getResultList();

        return result;
   }

Is there anyway for us to add orderby to the query and make it order by the primary key without specify the primary column as the expression? I mean, is there a Key/Constant or something in JPA meaning a primary key column of any entity, or a util method to retrieve it?

Quincy
  • 4,393
  • 3
  • 26
  • 40

1 Answers1

11

This information is available via metamodel. Something as follows should work in case of singular id attribute (not tested, so likely some problems, especially with generics, but approach in general is this):

public <T> SingularAttribute<? super T, ?> getIdAttribute(EntityManager em, 
                                                          Class<T> clazz) {
    Metamodel m = em.getMetamodel();
    IdentifiableType<T> of = (IdentifiableType<T>) m.managedType(clazz);
    return of.getId(of.getIdType().getJavaType());
}

//usage
SingularAttribute idAttribute = getIdAttribute(em, entity);
Path<?> pathToId = root.get(idAttribute);
query.orderBy(builder.asc(pathToId));

When entities that use IdClass should also be supported, solution is bit more complex, but possible with methods provided by IdentifiableType.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135