代码之家  ›  专栏  ›  技术社区  ›  flybywire

如何知道类是否映射为休眠实体?

  •  4
  • flybywire  · 技术社区  · 15 年前

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

    3 回复  |  直到 7 年前
        1
  •  5
  •   Mike Q    15 年前

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

    较好的解决方案

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

    原始答案:

    boolean isHibernateEntity = sessionFactory.getClassMetdata( Hibernate.getClass( yourObject ) ) != null;
    
        2
  •  0
  •   Angelo Ortega    7 年前

    这里没有 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;
    }
    
        3
  •  0
  •   Ladislavovic    7 年前

    现在,您可以通过 javax.persistence.metamodel.Metamodel 来自JPA 2。或 org.hibernate.Metamodel 如果你不使用JPA。例子:

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