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?
In Spring Data JPA we can map an entity to a specific table by using @Table annotation where we can specify schema and name. But Spring Data JDBC uses a NamingStrategy to map an entity to a table name by converting the entities class name.
The easiest way to set a custom SQL table name is to annotate the entity with @javax. persistence. Table and define its name parameter: @Entity @Table(name = "ARTICLES") public class Article { // ... }
The find() method used to retrieve an entity defined as below in the EntityManager interface. T find(Class<T> entityClass, Object primaryKey) – Returns entity for the given primary key. It returns null if entity is not found in the database.
The JPA specification requires the @Entity annotation. It identifies a class as an entity class. You can use the name attribute of the @Entity annotation to define the name of the entity. It has to be unique for the persistence unit, and you use it to reference the entity in your JPQL queries.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With