How can I know if a Class is mapped as a Hibernate entity?
I have an Object. Ho开发者_JS百科w can I know if its class is mapped to a table in Hibernate?
EDIT: My original answer works but will initialise unitialised proxies, which may be undesirable.
Better solution
boolean isHibernateEntity = sessionFactory.getClassMetadata( HibernateProxyHelper.getClassWithoutInitializingProxy( yourObject ) ) != null;
Original answer:
boolean isHibernateEntity = sessionFactory.getClassMetdata( Hibernate.getClass( yourObject ) ) != null;
This way you can get all entities managed by Hibernate: sessionFactory.getMetamodel()
. So to sum up:
boolean isHibernateEntity(Object obj) {
Class<?> cl = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
for (EntityType<?> entity : sessionFactory.getMetamodel().getEntities())
if (entity.getJavaType().equals(cl))
return true;
return false;
}
Now you can identify if a class is an entity or not by javax.persistence.metamodel.Metamodel
from JPA 2.0. Or org.hibernate.Metamodel
if you do not use JPA. Example:
public boolean isEntity(Class<?> clazz){
Metamodel metamodel = entityManager.getMetamodel();
try {
metamodel.entity(clazz);
} catch (IllegalArgumentException e) {
// NOTE: the exception means the class is NOT an entity. There is no reason to log it.
return false;
}
return true;
}
And here without sessionFactory
:
private boolean isEntityClass(Object o){
if(o != null){
Type[] interfaces = o.getClass().getGenericInterfaces();
for(Type interf : interfaces)
if(interf.equals(HibernateProxy.class))
return true;
}
return false;
}
精彩评论