I wanted to know if there is a way to get all the Entities classes and their metadata for a specific persistent unit in JPA.
By metadata I mean not only the fields, but also their column name, lenght, precision, datatype, and also the table name and anything that I can get. I tried with the metamodel but I think that's more for the JPQL queries only.
I need to be able to show the user all the active Entities for some PU, and I don't want to hardcode them in some array or in a database, I want the API to tell me what Entities does it have. And also, if it is possible, get the managed instances for every entity.
I guess I could try using reflection to get all the classes with the @Entity annotation, but it would not be pretty, and it would be harder to know which belongs to a specific PU, so if the api already exposes this info it would be great.
I would prefer a JPA compliant solution but if not possible, an Hibernate or EclipseLink specific answer would do it.
Thanks!
JPA requires that you accompany each persistent class with persistence metadata. This metadata serves three primary purposes: To identify persistent classes. To override default JPA behavior. To provide the JPA implementation with information that it cannot glean from simply reflecting on the persistent class.
You can use the @PersistenceContext annotation to inject an EntityManager in an EJB 3.0 client (such as a stateful or stateless session bean, message-driven bean, or servlet). You can use @PersistenceContext attribute unitName to specify a persistence unit by name, as Example 29-13 shows.
@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.
The find() method used to retrieve an entity defined as below in the EntityManager interface. T find(Class<T> entityClass, Object primaryKey) – Returns entity for the given primary key. It returns null if entity is not found in the database.
Yes you can get all the entities and the corresponding meta data information about the enitities from EntityManager
.
EntityManager.getMetamodel()
will give you access to the Metamodel
interface from where you can access EntityType
and ManagedType
to get the attributes of the entity.
Entities are independent of any persistence unit when they are defined. They are associated with a persistence unit in its definition, in persistence.xml. EntityManagerFactory that manages the entity managers for a given persistent unit doesn't seem to have any API to get the list of entities it manages. SessionFactory of Hibernate, counterpart of EntityManagerFactory, does have APIs to get hold of the class metadata (http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/SessionFactory.html).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With