【问题标题】:How to obtain Class from JPA entity name?如何从 JPA 实体名称中获取 Class?
【发布时间】:2015-12-30 21:17:02
【问题描述】:

有什么办法可以查到

  java.lang.Class 

那个有

@Entity(name = "X")?

换句话说,使用实体名称来获取实体的类名,当然是在运行时:)

【问题讨论】:

标签: class jpa entity


【解决方案1】:

所有注册的@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;
}

【讨论】:

  • 这个解决方案有效,但是我们有数千个实体,每次循环都很昂贵,,,,
  • @amitsalyan:如果需要多次映射,可以很容易地在映射中缓存映射,实体名称为键,类实例为值
【解决方案2】:

4 年前,我在 JPA 规范中提出了一个问题,即能够按实体名称加载实体,但在这件事上仍然没有进展: https://github.com/javaee/jpa-spec/issues/85

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2018-03-02
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多