我有一个对象。我怎么知道它的类是否映射到Hibernate中的表?
编辑:我的原始答案有效但会初始化单元化代理,这可能是不可取的。
好的解决方案
boolean isHibernateEntity = sessionFactory.getClassMetadata( HibernateProxyHelper.getClassWithoutInitializingProxy( yourObject ) ) != null;
原始答案:
boolean isHibernateEntity = sessionFactory.getClassMetdata( Hibernate.getClass( yourObject ) ) != null;
这里没有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;
}
现在,您可以通过JPA 2.0中的javax.persistence.metamodel.Metamodel
识别某个类是否是实体。或者如果你不使用JPA,org.hibernate.Metamodel
。例:
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;
}