6

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 :)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
amitsalyan
  • 658
  • 1
  • 8
  • 29
  • Of interest, possibly answering the question entirely if you read through all answers: http://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java . – Gimby Oct 02 '15 at 16:09

2 Answers2

8

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;
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • This solution works, however we have thousands of entities and looping through every time is expensive,,,, – amitsalyan Oct 02 '15 at 16:20
  • 2
    @amitsalyan: If you need to do the mapping multiple times, it's easy to cache mappings in a map with entity names as keys, and Class instances as values – OndroMih Oct 03 '15 at 23:02
0

I've raised an issue in the JPA spec to be able to load entity by entity name 4 years ago and still no development on the matter: https://github.com/javaee/jpa-spec/issues/85

Petar Tahchiev
  • 4,336
  • 4
  • 35
  • 48