检索JPA中通用实体的主键列定义 [英] Retrieve primary key column definition of a generic entity in JPA
问题描述
假设我有一个使用JPA列出实体的通用方法
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;
}
反正我们是否可以添加 orderby
到查询并通过主键进行排序,而无需将主列指定为表达式?我的意思是,在JPA中是否存在 Key
/ Constant
或JPA中的任何内容,这意味着任何实体的主键列,或者util方法来检索它?
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?
推荐答案
此信息可通过元模型。在奇数id属性的情况下(未测试,可能会有一些问题,因此可能会出现一些问题,尤其是对于泛型,但一般而言是这样):
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));
使用 IdClass 也应受支持,解决方案稍微复杂一些,但是可以使用 IdentifiableType 。
When entities that use IdClass should also be supported, solution is bit more complex, but possible with methods provided by IdentifiableType.
这篇关于检索JPA中通用实体的主键列定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!