0

I tried to write some common method (Java/Spring/JPA) to get first N entities from database. All entities has @Id annotation but id field could has various names. For example, entities with ids Table.tableId or Plate.plateId. Both tableId and plateId have @Id annotation, but field names are different (in code and in database). I cannot change field names. I tried to sort asc and setMaxResults via JPA Criteria API, but I cannot find the way to sort by id.

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

public class EntityHelper {

    protected final EntityManager entityManager;

    public List<ENTITY> getFirstEntities(Class<ENTITY> entityClass, int count) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<ENTITY> criteriaQuery = criteriaBuilder.createQuery(entityClass);
        Root<ENTITY> root = criteriaQuery.from(entityClass);
        criteriaQuery.select(root);
//      HOW TO SORT by ID???  criteriaQuery.orderBy(criteriaBuilder.asc());

        TypedQuery<ENTITY> query = entityManager.createQuery(criteriaQuery);
        return query.setMaxResults(count).getResultList();
    }
}

What I need to use to make asc sort by id? Or maybe is there any another way to implement such method? JPA 2.1.

Yuriy Alevohin
  • 941
  • 7
  • 18
  • The column names don't have to match the entity field names necessarily. You could use a [mapped super class](http://stackoverflow.com/a/5258090/1199132) to declare a generic id field and then override it in each of the subclasses that use a different id column name. Alternatively, you could try to do it with an interface, but I'm not sure it'll work. – Aritz Dec 26 '16 at 13:03

1 Answers1

1

For a similar purpose using Hibernate, I get the name of the id property of an entity thru ClassMetadata.getIdentifierPropertyName(). Using JPA, it seems that the same can be achieved thru something like this (i didn't try, just read javadoc):

IdentifiableType identifiableType = (IdentifiableType) entityManager.getMetamodel().managedType(entityClass);
String idPropertyName = identifiableType.getId(entityClass).getName();
criteriaQuery.orderBy(criteriaBuilder.asc(root.get(idPropertyName)));
jorgegm
  • 166
  • 5