Search code examples
stringclassjpaentity

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


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

Some part of legacy code does only have a String value of the table (CUSM_LANGUAGE in this example), and I need to find the entity class name (LanguageEntity)

@Entity
@Table(name = "CUSM_LANGUAGE")
public class LanguageEntity implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    @Column(name = "LANG_DESCRIPTION")
    private String description = null;
    ....

Solution

  • I guess it strongly depends on JPA which you're using.

    In JPA 2.0 you have class: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html

    This class has getMetamodel() method which I expect to contains all information about your database.

    In Metamodel (http://docs.oracle.com/javaee/6/api/javax/persistence/metamodel/Metamodel.html) you have getEntities() that's how we get: EntityType

    I'm not sure how get from EntityType information about table it is using. But even it's not directly possible (which I doubt) you can do it as described below.

    Because you have legacy code I expect you have JPA < 2.0 which doesn't have this getMetamodel method. That's why informations you can get about entities strongly depends on specific JPA you're using.

    However if you have bunch of classes you care about (and you can create this list easily) you can create index on your own:

    String tableNameOfEntityClass = LanguageEntity.class.getAnnotation(Table.class).name();
    

    So you can put all classes you care to list and then create map with key tableName and value refering class.

    Of course it's not very useful without Metamodel which I described above because as well you can create ready map instead of List with entity classes.