我怎么知道一个Class是否被映射为Hibernate实体?

问题描述 投票:4回答:3

我有一个对象。我怎么知道它的类是否映射到Hibernate中的表?

java hibernate
3个回答
5
投票

编辑:我的原始答案有效但会初始化单元化代理,这可能是不可取的。

好的解决方案

boolean isHibernateEntity = sessionFactory.getClassMetadata( HibernateProxyHelper.getClassWithoutInitializingProxy( yourObject ) ) != null;

原始答案:

boolean isHibernateEntity = sessionFactory.getClassMetdata( Hibernate.getClass( yourObject ) ) != null;

0
投票

这里没有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
投票

现在,您可以通过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;
}
© www.soinside.com 2019 - 2024. All rights reserved.