如何从JPA实体名称中获取Class?
How to obtain Class from JPA entity name?
有没有办法找出
java.lang.Class
那就是
@Entity(name = "X")?
换句话说,使用实体名称获取实体的类名,当然是在运行时:)
所有已注册的 @Entity
都可以在 MetaModel#getEntities()
. It returns a List<EntityType<?>>
whereby the EntityType
has a getName()
method representing the @Entity(name)
and a getJavaType()
representing the associated @Entity
class. The MetaModel
instance is in turn available by EntityManager#getMetaModel()
之前获得。
换句话说,这是实用方法的风格:
public static Class<?> getEntityClass(EntityManager entityManager, String entityName) {
for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
if (entityName.equals(entity.getName())) {
return entity.getJavaType();
}
}
return null;
}
我在 JPA 规范中提出了一个问题,以便能够在 4 年前通过实体名称加载实体,但仍然没有关于此事的进展:
https://github.com/javaee/jpa-spec/issues/85
有没有办法找出
java.lang.Class
那就是
@Entity(name = "X")?
换句话说,使用实体名称获取实体的类名,当然是在运行时:)
所有已注册的 @Entity
都可以在 MetaModel#getEntities()
. It returns a List<EntityType<?>>
whereby the EntityType
has a getName()
method representing the @Entity(name)
and a getJavaType()
representing the associated @Entity
class. The MetaModel
instance is in turn available by EntityManager#getMetaModel()
之前获得。
换句话说,这是实用方法的风格:
public static Class<?> getEntityClass(EntityManager entityManager, String entityName) {
for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
if (entityName.equals(entity.getName())) {
return entity.getJavaType();
}
}
return null;
}
我在 JPA 规范中提出了一个问题,以便能够在 4 年前通过实体名称加载实体,但仍然没有关于此事的进展: https://github.com/javaee/jpa-spec/issues/85