java 检索 JPA 实体列表和元数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11945041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving JPA Entity List and metadata
提问by Frank Orellana
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.
我想知道是否有办法获取 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.
我所说的元数据不仅指字段,还指它们的列名、长度、精度、数据类型,以及表名和我能得到的任何东西。我尝试使用元模型,但我认为这仅适用于 JPQL 查询。
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.
我需要能够向用户显示某些 PU 的所有活动实体,并且我不想将它们硬编码到某个数组或数据库中,我希望 API 告诉我它有哪些实体。而且,如果可能的话,获取每个实体的托管实例。
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.
我想我可以尝试使用反射来获取所有带有 @Entity 注释的类,但它不会很漂亮,而且很难知道哪个属于特定的 PU,所以如果 api 已经公开了这个信息,那就是伟大的。
I would prefer a JPA compliant solution but if not possible, an Hibernate or EclipseLink specific answer would do it.
我更喜欢 JPA 兼容的解决方案,但如果不可能,Hibernate 或 EclipseLink 特定的答案可以做到。
Thanks!
谢谢!
回答by Meiyappan Kannappa
Yes you can get all the entities and the corresponding meta data information about the enitities from EntityManager
.
是的,您可以从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.
EntityManager.getMetamodel()
将使Metamodel
您可以访问界面,从中可以访问EntityType
并ManagedType
获取实体的属性。
回答by Vikdor
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).
实体在定义时独立于任何持久性单元。它们在其定义中与persistence.xml 中的持久性单元相关联。管理给定持久单元的实体管理器的 EntityManagerFactory 似乎没有任何 API 来获取它管理的实体列表。Hibernate 的 SessionFactory,EntityManagerFactory 的对应物,确实有 API 来获取类元数据(http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/SessionFactory.html)。