Reputation: 678
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 :)
Upvotes: 6
Views: 3752
Reputation: 4386
I've raised an issue in the JPA spec to be able to load entity by entity name in 2014:
https://github.com/jakartaee/persistence/issues/85
This was finally implemented seven years later, in 2023. It is currently part of Jakarta Persistence 3.2.0-B02, a prerelease version of the next planned release.
Upvotes: 1
Reputation: 21123
The ability to get an entity by name is being added to the upcoming Jakarta Persistence 3.2 by way of the new Metamodel.entity(String entityName)
method.
public static Class<?> getEntityClass(EntityManager entityManager,
String entityName) {
return entityManager.getMetamodel().entity(entityName).getJavaType();
}
Upvotes: 0
Reputation: 1108722
All registered @Entity
s 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;
}
Upvotes: 8