The title is self explanatory.
I would be glad to hear solutions, thanks.
The title is self explanatory.
I would be glad to hear solutions, thanks.
There's a shorter approach than listed so far:
Reflections r = new Reflections(this.getClass().getPackage().getName());
Set<Field> fields = r.getFieldsAnnotatedWith(Id.class);
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
There's a shorter approach than listed so far:
Reflections r = new Reflections(this.getClass().getPackage().getName());
Set<Field> fields = r.getFieldsAnnotatedWith(Id.class);
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.
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;
}
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();
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.
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();
}
© 2022 - 2024 — McMap. All rights reserved.