javatar
javatar

Reputation: 4621

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

The title is self explanatory.

I would be glad to hear solutions, thanks.

Upvotes: 5

Views: 7773

Answers (7)

Frank S
Frank S

Reputation: 141

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();

Upvotes: 2

Hartmut Pfarr
Hartmut Pfarr

Reputation: 6139

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

Upvotes: 1

KendallV
KendallV

Reputation: 396

There's a shorter approach than listed so far:

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

Upvotes: 4

Roberto S.
Roberto S.

Reputation: 11

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.

Upvotes: 1

DataNucleus
DataNucleus

Reputation: 15577

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

Upvotes: 4

James DW
James DW

Reputation: 1815

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

Upvotes: 2

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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.

Upvotes: 3

Related Questions