JPA 2 元模型 是 JPA 2 中类型安全查询的基础。生成的类允许您使用静态字段引用来引用实体属性,而不是字符串。(元模型类是实体类的完全限定类名后跟一个下划线(_))。
听起来很有前景,但许多使用 Maven 的人在使用生成和编译元模型时遇到了困难。《Hibernate JPA 2 Metamodel Generator 指南》提供了一些解决方案。我找到了另一个,看起来更优雅。
让我们先回顾一下问题
- Maven 在编译阶段编译类
- Java 6 编译器允许注解处理器挂钩其中
- 注解处理器被允许生成 Java 源文件(JPA 2 元模型就是这种情况)
- Maven 不会执行一个额外的编译步骤来编译注解处理器生成的 Java 源文件
我发现,在生成源代码阶段,可以使用 Maven 编译器插件来运行注解处理器!这实际上成为了一个代码生成步骤。然后,只有一个缺点。令人难以置信的是,Maven 没有内置的方式来编译生成的源文件。因此,我们需要添加一个额外的插件(build-helper-maven-plugin),它只是添加了一个额外的源文件夹(我真的无法相信编译器插件没有提供这个功能)。在编译阶段,我们可以禁用注解处理器来加快编译速度并避免第二次生成元模型。
以下是配置,供您复制粘贴。将其添加到您的 POM 中的<plugins>部分。
<!-- Compiler plugin enforces Java 1.6 compatibility and controls execution of annotation processors --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-proc:none</compilerArgument> </configuration> <executions> <execution> <id>run-annotation-processors-only</id> <phase>generate-sources</phase> <configuration> <compilerArgument>-proc:only</compilerArgument> <!-- If your app has multiple packages, use this include filter to execute the processor only on the package containing your entities --> <!-- <includes> <include>**/model/*.java</include> </includes> --> </configuration> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> <!-- Build helper plugin adds the sources generated by the JPA 2 annotation processor to the compile path --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.5</version> <executions> <execution> <phase>process-sources</phase> <configuration> <sources> <source>${project.build.directory}/generated-sources/annotations</source> </sources> </configuration> <goals> <goal>add-source</goal> </goals> </execution> </executions> </plugin>
元模型源文件生成到target/generated-sources/annotations目录。
请注意,如果您在Java包中引用了元模型,您需要过滤注解处理器,使其仅在包含实体类的包上运行。
我们将在Weld架构的1.0.1.Beta1版本中实现此方法,该版本即将推出。
附加材料:Eclipse配置
在此期间,我还可以向您展示如何在Eclipse中启用JPA 2元模型生成。(Max可能会纠正我。他是Eclipse工具的权威人士,所以请听他的意见)。
首先,将以下依赖项添加到您的POM中
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-jpamodelgen</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency>
然后,在项目根目录中填充以下内容的.factorypath文件
<factorypath> <factorypathentry kind="PLUGIN" id="org.eclipse.jst.ws.annotations.core" enabled="true" runInBatchMode="false"/> <factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/hibernate-jpamodelgen/1.0.0.Final/hibernate-jpamodelgen-1.0.0.Final.jar" enabled="true" runInBatchMode="false"/> <factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.0.Final/hibernate-jpa-2.0-api-1.0.0.Final.jar" enabled="true" runInBatchMode="false"/> </factorypath>
在Eclipse中刷新项目。现在右键单击项目并选择
Properties > Java Compiler > Annotation Processing
启用项目特定设置并启用注解处理。当提示构建项目时,按OK并再次按OK。现在,Eclipse还应生成您的JPA 2元模型。
享受类型安全的查询!