Common method to select first N entities from database in JPA

682 views Asked by At

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.

1

There are 1 answers

0
jorgegm On BEST ANSWER

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)));