Listing JPA Entities and Metadata

I wanted to know if there is a way to get all Entities classes and their metadata for a specific constant unit in JPA.

By metadata, I mean not only the fields, but also their column name, length, precision, data type, as well as the name of the table and everything I can get. I tried with a metamodel, but I think more for JPQL queries.

I need to show the user all active objects for some PU, and I don’t want to hardcode them in any array or in the database, I want the API to tell me what Entities have. And also, if possible, get managed instances for each object.

I think I could try using reflection to get all classes with @Entity annotation, but that would not be very pretty, and it would be harder to know what belongs to a particular PU, so if the api already provides this information it would be great .

I would prefer a JPA-compatible solution, but if that doesn't work, then the answer to this question will be answered in Hibernate or EclipseLink.

Thanks!

+6
source share
2 answers

Yes, you can get all objects and relevant metadata information about 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 object.

+8
source

Entities are independent of any conservation unit when they are defined. They are associated with the unit of persistence in its definition in persistence.xml. The EntityManagerFactory, which manages the entity managers for this persistent device, does not seem to have any API for retrieving the list of entities it manages. SessionFactory of Hibernate, an analogue of EntityManagerFactory, has an API for obtaining class metadata ( http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/SessionFactory.html ).

+2
source

Source: https://habr.com/ru/post/922791/


All Articles