Retrieve primary key column definition of a generic entity in JPA

与世无争的帅哥 提交于 2019-12-06 12:38:44

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.

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