如何从持久性单元获取所有@Entity类? [英] How can I get all @Entity classes from a Persistence Unit?

查看:630
本文介绍了如何从持久性单元获取所有@Entity类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个独立的实用程序,给定一个包含JPA-2注释持久性单元的jar,需要以编程方式获取所有我的列表@Entity类在特定的持久性单元中。

I'm writing a standalone utility program which, given a jar containing a JPA-2 annotated persistence unit, needs to programmatically get a list of all my @Entity classes in a particular persistence unit.

我想决定采用哪种方法来获取这些信息,以及为什么;或者如果还有其他更好的方法我没有想到。

I'd like to decide which of 2 approaches would be the way to go to get this information, and why; or if there is another better way I haven't thought of.

Java程序放jar在类路径上,使用JavaSE方法从jar中的类创建持久性单元。然后它使用javax.persistence类来获取JPA Metamodel,从中拉回类令牌列表。

Java program puts jar on the classpath, creates persistence unit from the classes in the jar using JavaSE methodologies. Then it uses the javax.persistence classes to get the JPA Metamodel, pull back list of class tokens from that.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("MY_ PERSISTENCE_UNIT");
Metamodel mm = emf.getMetamodel();

// loop these, using getJavaType() from Type sub-interface to get 
// Class tokens for managed classes.
mm.getManagedTypes();



解决方案2



程序扫描目录和指定jar中的文件用于persistence.xml文件,然后找到具有指定持久性单元名称的文件。然后XPath文件获取< class> XML元素的列表,并从那里读取完全限定的类名。从名称,构建类标记。

Solution 2

Program scan the directories and files inside the specified jar for persistence.xml files, then finds one with the specified persistence unit name. Then XPath the file to get the list of <class> XML elements and read the fully qualified class names from there. From names, build class tokens.


  • 我是如果可能的话,喜欢采用方法1。

  • 此实用程序不会在容器内运行,但jar是一个旨在在其中运行的EJB项目。这将是一个什么问题?

  • 该实用程序将在类路径上提供Open-EJB,以获取所有Java EE 6类的实现。

  • 即使EJB项目是为了在Hibernate上运行,该实用程序不应该是特定于Hibernate的。

  • 是否有任何绊脚石?

  • I'd like to go with approach 1 if possible.
  • This utility will NOT run inside a container, but the jar is an EJB project designed to run inside one. How will this be a problem?
  • The utility will have Open-EJB available on the classpath to get implementations of all the Java EE 6 classes.
  • Even though the EJB project is built to run on Hibernate, the utility should not be Hibernate-specific.
  • Are there any stumbling blocks?

推荐答案

如果你的jar格式正确(persistence.xml在正确的位置 - 在META-INF文件夹中),那么一切看起来都很好。

If Your jar is well-formed (persistence.xml at the right place - in the META-INF folder), then all looks fine.

没有必要在容器内运行实用程序,JPA不是JavaEE规范的一部分。

It is not necessary to run your utility inside a container, JPA is not a part of JavaEE specs.

这篇关于如何从持久性单元获取所有@Entity类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆