Try this:
@PersistenceUnit
private EntityManagerFactory emf;
Metamodel metamodel = emf.getMetamodel();
metamodel.entity(MyEntity.class).getId();
Question
I'm using JPA2 (Hibernate 4) and have a bunch of @Entity classes with my PKs defined using @Id. How can I programatically retrieve the fieldnames of the PKs of each entity class?
The business case for this is that I want to use Spring's BeanUtils.copyProperties method to copy over entity objects, but want to make sure that I ignore the id fields of my entities while copying.
Is there a way to find this information? Does JPA provide this information? I realize that I can use reflection to go through every class, but hoped there would be an easier solution. I looked into scanning the PropertyDescriptor
s of the class, but cannot seem to find any method on the PropertyDescriptor that would give me the annotations of a property.
Solution
Try this:
@PersistenceUnit
private EntityManagerFactory emf;
Metamodel metamodel = emf.getMetamodel();
metamodel.entity(MyEntity.class).getId();