Reputation: 488
I need to retrieve the database table name of a certain entity using only my EntityManager instance, is that possible?
Or any way to load all mapped tables with related entity classes.
PS.: I'm using Hibernate v4.2.7 without Annotations
Upvotes: 1
Views: 1468
Reputation: 26502
You can get that from hibernate SessionFactory once you strip it out of the EntityManager:
@PersistenceContext
EntityManager entityManager;
public String getTableName(Class entityClass){
SessionFactory sessionFactory = ((Session) entityManager.getDelegate()).getSessionFactory();
ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
AbstractEntityPersister entityPersister
= (AbstractEntityPersister) sessionFactoryImpl.getEntityPersister(classMetadata.getEntityName());
return entityPersister.getTableName();
}
Could not find appropriate API to use plain EntityManager. If you are allowed to work with the implementation then this worked for me.
Upvotes: 2
Reputation: 488
Maciej answer was missing some code and I found a way to do with less steps:
private String getTableName ( Class entityClass ) {
SessionFactory sessionFactory = ( ( Session ) getEntityManager().getDelegate() ).getSessionFactory();
AbstractEntityPersister persister = ( AbstractEntityPersister ) sessionFactory.getClassMetadata( entityClass );
return persister.getTableName();
}
I have tried to edit his answer but was rejected =/
Upvotes: 1