How to get the field annotated with @Id in EJB3 (JPA) and Hibernate?

左心房为你撑大大i 提交于 2019-12-06 08:33:14

问题


The title is self explanatory.

I would be glad to hear solutions, thanks.


回答1:


There's a shorter approach than listed so far:

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



回答2:


JPA2 has a metamodel. Just use that, and you then stay standards compliant. The docs of any JPA implementation ought to give you enough information on how to access the metamodel




回答3:


I'm not a java programmer, nor a user of Hibernate annotations... but I probably can still help.

This information is available in the meta data. You can get them from the session factory. I looks like this:

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

I found this API documentation.




回答4:


I extended this answer: How to get annotations of a member variable?

Try this:

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



回答5:


ClassMetadata.getIdentifierPropertyName() returns null if the entity has a composite-id with embedded key-many-to-one. So this method does not cover those situations.




回答6:


A bit late to the party, but if you happen to know your entities have only one @Id annotation and know the type of the id (Integer in this case), you can do this :

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



回答7:


This is working for EclipseLink 2.6.0, but I don't expect any differences in Hibernate space:

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


来源:https://stackoverflow.com/questions/7647549/how-to-get-the-field-annotated-with-id-in-ejb3-jpa-and-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!