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?
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;
}