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.