如何在EJB3(JPA)和Hibernate中获得带@Id注释的字段?

如何在EJB3(JPA)和Hibernate中获得带@Id注释的字段?,hibernate,jpa,annotations,ejb-3.0,Hibernate,Jpa,Annotations,Ejb 3.0,标题不言自明 我很高兴听到解决方案,谢谢。我不是java程序员,也不是Hibernate注释的用户。。。但我可能仍然可以帮忙 这些信息可以在元数据中找到。您可以从会话工厂获取它们。我看起来像这样: ClassMetadata classMetadata = getSessionFactory().getClassMetadata(myClass); string identifierPropertyName = classMetadata.getIdentifierPropertyName();

标题不言自明


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

我不是java程序员,也不是Hibernate注释的用户。。。但我可能仍然可以帮忙

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

ClassMetadata classMetadata = getSessionFactory().getClassMetadata(myClass);
string identifierPropertyName = classMetadata.getIdentifierPropertyName();
我找到了。

我扩展了这个答案:

试试这个:

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;
}
String findIdField(类cls){
for(字段:cls.getDeclaredFields()){
类类型=field.getType();
字符串名称=field.getName();
Annotation[]annotations=field.getDeclaredAnnotations();
for(int i=0;i
JPA2有一个元模型。只要使用它,你就可以遵守标准。任何JPA实现的文档都应该为您提供有关如何访问元模型的足够信息。如果实体具有嵌入键多对一的复合id,则getIdentifierPropertyName()返回null。
因此,此方法不包括这些情况。

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

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

这适用于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();
     }

参加聚会有点晚,但是如果您碰巧知道您的实体只有一个@Id注释,并且知道Id的类型(在本例中为整数),您可以这样做:

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

您需要名称还是值也可以?实际上我需要名称本身,而不是值。您好,我使用spring3和hibernate3,据我所知,这种组合还不支持jpa2。Hibernate 3.6显然支持jpa2。Spring也是JPA2.0的答案