Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain Class from JPA entity name?

Tags:

class

jpa

entity

Is there a way to find out the

  java.lang.Class 

that is the one having

@Entity(name = "X")?

In other words use the Entity Name to get the classname of the Entity, of course at runtime :)

like image 479
amitsalyan Avatar asked Mar 15 '23 14:03

amitsalyan


1 Answers

All registered @Entitys are available by MetaModel#getEntities(). It returns a List<EntityType<?>> whereby the EntityType has a getName() method representing the @Entity(name) and a getJavaType() representing the associated @Entity class. The MetaModel instance is in turn available by EntityManager#getMetaModel().

In other words, here's the approach in flavor of an utility method:

public static Class<?> getEntityClass(EntityManager entityManager, String entityName) {
    for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
        if (entityName.equals(entity.getName())) {
            return entity.getJavaType();
        }
    }

    return null;
}
like image 132
BalusC Avatar answered Mar 17 '23 03:03

BalusC