简体   繁体   中英

Common method to select first N entities from database in JPA

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM