Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

entity

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?

like image 779
marabol Avatar asked Feb 26 '10 13:02

marabol


People also ask

How do you map entity and table?

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.

How do you name a table entity?

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 { // ... }

Which method in JPA is used to retrieve the entity based on its primary keys?

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.

How do you indicate entity in JPA?

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.


1 Answers

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; } 
like image 98
Daniel Szalay Avatar answered Sep 19 '22 18:09

Daniel Szalay