【发布时间】:2015-12-30 21:17:02
【问题描述】:
有什么办法可以查到
java.lang.Class
那个有
@Entity(name = "X")?
换句话说,使用实体名称来获取实体的类名,当然是在运行时:)
【问题讨论】:
-
感兴趣,如果您通读所有答案,可能会完全回答这个问题:stackoverflow.com/questions/4296910/…。
有什么办法可以查到
java.lang.Class
那个有
@Entity(name = "X")?
换句话说,使用实体名称来获取实体的类名,当然是在运行时:)
【问题讨论】:
所有注册的@Entitys 都可以通过MetaModel#getEntities() 获得。它返回一个List<EntityType<?>>,其中EntityType 有一个代表@Entity(name) 的getName() 方法和一个代表关联@Entity 类的getJavaType()。 MetaModel 实例反过来由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;
}
【讨论】:
4 年前,我在 JPA 规范中提出了一个问题,即能够按实体名称加载实体,但在这件事上仍然没有进展: https://github.com/javaee/jpa-spec/issues/85
【讨论】: