如何在运行时检索JPA中的实体的映射表名称?

mar*_*bol 29 java entity jpa

是否可以确定实体的本机表名称?

如果存在Table注释,则很容易:

entityClass.getAnnotation(Table.class).name()
Run Code Online (Sandbox Code Playgroud)

但是如果没有Table注释呢?

Hibernate通过Configuration类提供此信息:

configuration.getClassMapping(entityClass.getSimpleName()).getTable().getName()
Run Code Online (Sandbox Code Playgroud)

JPA中有类似的东西吗?

Dan*_*lay 14

这是我使用EclipseLink的方法(没有映射文件):

/**
 * Returns the table name for a given entity type in the {@link EntityManager}.
 * @param em
 * @param entityClass
 * @return
 */
public static <T> String getTableName(EntityManager em, Class<T> entityClass) {
    /*
     * Check if the specified class is present in the metamodel.
     * Throws IllegalArgumentException if not.
     */
    Metamodel meta = em.getMetamodel();
    EntityType<T> entityType = meta.entity(entityClass);

    //Check whether @Table annotation is present on the class.
    Table t = entityClass.getAnnotation(Table.class);

    String tableName = (t == null)
                        ? entityType.getName().toUpperCase()
                        : t.name();
    return tableName;
}
Run Code Online (Sandbox Code Playgroud)

  • 不认为这是正确的方法,例如该方法将为名称为 SomeComplexName 的实体返回什么? (2认同)

Dat*_*eus 3

如果不存在表注释(并且没有 ORM.xml),则在 JPA 中,表名称是根据类名称形成的(请参阅 JPA 规范)。那么为什么你需要一个访问器方法呢?

请参阅http://www.datanucleus.org/products/accessplatform_2_0/jpa/orm/datastore_identifiers.html

  • 我想避免再次实现该算法。我也想避免解析 XML 映射文件。但我已经想到,无法向 JPA 实现询问真实的表名称。多谢。 (3认同)