开发者

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜