【问题标题】:How to get the field annotated with @Id in EJB3 (JPA) and Hibernate?如何在 EJB3 (JPA) 和 Hibernate 中获取带有 @Id 注释的字段?
【发布时间】:2011-11-30 15:28:28
【问题描述】:

标题是不言自明的。

我很高兴听到解决方案,谢谢。

【问题讨论】:

  • 需要名字,还是值也可以?
  • 其实我需要的是名字本身,而不是值。

标签: hibernate jpa annotations ejb-3.0


【解决方案1】:

我不是 Java 程序员,也不是 Hibernate 注释的用户......但我可能仍然可以提供帮助。

此信息在元数据中可用。您可以从会话工厂获取它们。我看起来像这样:

ClassMetadata classMetadata = getSessionFactory().getClassMetadata(myClass);
string identifierPropertyName = classMetadata.getIdentifierPropertyName();

我找到了this API documentation

【讨论】:

    【解决方案2】:

    我扩展了这个答案:How to get annotations of a member variable?

    试试这个:

    String findIdField(Class cls) {
        for(Field field : cls.getDeclaredFields()){
            Class type = field.getType();
            String name = field.getName();
            Annotation[] annotations = field.getDeclaredAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                if (annotations[i].annotationType().equals(Id.class)) {
                    return name;
                }
            }
        }
        return null;
    }
    

    【讨论】:

      【解决方案3】:

      JPA2 有一个元模型。只需使用它,然后您就可以保持符合标准。任何 JPA 实现的文档都应该为您提供有关如何访问元模型的足够信息

      【讨论】:

      • 嗨,我使用 spring3 和 hibernate3,据我所知,这种组合还不支持 jpa2。
      • Hibernate 3.6 显然支持 JPA2。春天也
      • 这是 JPA 2.0 的答案stackoverflow.com/a/4107005/1572286
      【解决方案4】:

      ClassMetadata.getIdentifierPropertyName() 如果实体具有包含嵌入键多对一的复合 ID,则返回 null。 所以这个方法不涵盖这些情况。

      【讨论】:

        【解决方案5】:

        有一个比目前列出的更短的方法:

        Reflections r = new Reflections(this.getClass().getPackage().getName());
        Set<Field> fields = r.getFieldsAnnotatedWith(Id.class);
        

        【讨论】:

          【解决方案6】:

          这适用于 EclipseLink 2.6.0,但我预计 Hibernate 空间不会有任何差异:

            String idPropertyName;
            for (SingularAttribute sa : entityManager.getMetamodel().entity(entityClassJpa).getSingularAttributes())
               if (sa.isId()) {
                  Preconditions.checkState(idPropertyName == null, "Single @Id expected");
                  idPropertyName = sa.getName();
               }
          

          【讨论】:

            【解决方案7】:

            聚会有点晚了,但是如果您碰巧知道您的实体只有一个 @Id 注释并且知道 id 的类型(在这种情况下为整数),您可以这样做:

            Metamodel metamodel = session.getEntityManagerFactory().getMetamodel();
            String idFieldName = metamodel.entity(myClass)
                .getId(Integer.class)
                .getName();
            

            【讨论】:

              猜你喜欢
              • 2011-12-07
              • 2016-07-16
              • 2010-10-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-12-18
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多