How to retrieve mapping table name for an entity in JPA at runtime?

marabol picture marabol · Feb 26, 2010 · Viewed 29.7k times · Source

Is it possible to determine the native table name of an entity?

If a Table annotation is present it's easy:

entityClass.getAnnotation(Table.class).name()

But what about if no Table annotation is present?

Hibernate provides this information via the Configuration class:

configuration.getClassMapping(entityClass.getSimpleName()).getTable().getName()

Is there something similar in JPA?

Answer

Daniel Szalay picture Daniel Szalay · Oct 17, 2014

This is the method I am using with EclipseLink (no mapping file):

/**
 * 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;
}