Retrieve primary key column definition of a generic entity in JPA

China☆狼群 提交于 2019-12-08 01:38:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16909236/retrieve-primary-key-column-definition-of-a-generic-entity-in-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!