在运行时检索 JPA 中实体的表名称的代码示例?

2023-11-29

我想列出我的 JPA 实体模型的所有数据库表名称,但我无法获得正确的实体类!

EntityManagerFactory factory;
Set<EntityType<?>> entities = factory.getMetamodel().getEntities();
for (EntityType entity: entities) {
    String tableName = entity.getClass().getAnnotation(Table.class).name();
    logger.debug("Entity name  = {}", entity.getName(); //This works
    logger.debug("Entity class = {}", entity.getClass().getName()); //This returns the runtime class of the object, and not the entity class!!
    logger.debug("Entity table = {}", entity.getClass().getAnnotation(Table.class).name()); //Nothing, because it does not find the correct class
}

Output:

Entity name  = PersonEntity
Entity class = org.hibernate.jpa.internal.metamodel.EntityTypeImpl
Entity table = ........ nothing, because this works on the EntityTypeImpl and not on the PersonEnity

如何获取实体类的表名称?


要回答这个问题,我们必须认识到JPA运行时类型包装了原始的@Entity注释的POJO。对非运行时类的简单测试将显示表名称是可访问的:

System.out.println("Table_Name: " + MyEntity.class.getAnnotation(Table.class).name());

因此,这里的技巧是访问正确的实体类引用,然后从那里调用所需的函数。

参考 API 进行实体类型Impl,我们可以看到它继承自抽象类型,它提供了方法“getJavaType()”,该方法返回对底层实体类的引用。有了这些知识,我们可以编写以下函数来获取与当前会话关联的每个实体类,以及与每个实体关联的每个表名称。

protected void testFunc() {
    Metamodel metamodel = entityManager.getMetamodel();
    for (EntityType<?> e : metamodel.getEntities()) {
        Class<?> entityClass = e.getJavaType();
        String entityTableName = entityClass.getAnnotation(Table.class).name();
        System.out.println("Table_Name: " + entityTableName);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在运行时检索 JPA 中实体的表名称的代码示例? 的相关文章

随机推荐