Search code examples
classjpaannotationsentity

Code example to retrieve table name for an entity in JPA in runtime?


I want to list all Database Table names for my JPA Entity model, but I can't get the correct Entity class!

EntityManagerFactory factory;
Set<EntityType<?>> entities = factory.getMetamodel().getEntities();
for (EntityType entity: entities) {
    String tableName = entity.getClass().getAnnotation(Table.class).name();
    logger.debug("Entity name  = {}", entity.getName(); //This works
    logger.debug("Entity class = {}", entity.getClass().getName()); //This returns the runtime class of the object, and not the entity class!!
    logger.debug("Entity table = {}", entity.getClass().getAnnotation(Table.class).name()); //Nothing, because it does not find the correct class
}

Output:

Entity name  = PersonEntity
Entity class = org.hibernate.jpa.internal.metamodel.EntityTypeImpl
Entity table = ........ nothing, because this works on the EntityTypeImpl and not on the PersonEnity

How do I get the Table name for the Entity Class?


Solution

  • OK, so if want do this with reflection. It should be pretty easy since this runtime class have to extends your class. If it wouldn't extends your class you won't be able to use it in your application.

    So you have to do something like below

        String myPackage = "com.company.";
        Class entityClass = y.getClass();
        while (!entityClass.getCanonicalName().startsWith(myPackage)) {
            entityClass = entityClass.getSuperclass();
        }
        Class classInYourPackage = entityClass;
    

    And you should get correct (your) class.

    Not tested, however that's the way it should work.

    EDIT: Not sure what package will be assigned by JPA to these runtime classes. So if code above doesn't work try with getSuperclass() method on your own.