Hibernate 如何生成 JPA 的 Metamodel

要在 Hibernate 中生成 JPA 的 Metamodel。

你只需要在 pom.xml 进行下面的 2 个操作就可以了。

添加依赖

在 POM 中添加下面的依赖。

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>5.6.3.Final</version>
        </dependency>

编译插件

在编译插件中,添加编译参数

                    <compilerArguments>
                        <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                    </compilerArguments>

完整的编译参数如下图

注意上图中的插件配置。

进行编译

运行命令:mvn compile

输出如下:

PS C:\WorkDir\USRealEstate\Source-Code\mls-common> mvn compile
[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------< com.ossez.usreio:mls-common >---------------------
[INFO] Building Mls-Common 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mls-common ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 5 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mls-common ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 35 source files to C:\WorkDir\USRealEstate\Source-Code\mls-common\target\classes
[INFO] /C:/WorkDir/USRealEstate/Source-Code/mls-common/src/main/java/com/ossez/usreio/mls/common/dao/factories/ListingMlsPhotoFactory.java: Some input files use or override a deprecated API.
[INFO] /C:/WorkDir/USRealEstate/Source-Code/mls-common/src/main/java/com/ossez/usreio/mls/common/dao/factories/ListingMlsPhotoFactory.java: Recompile with -Xlint:deprecation for details.
[INFO] /C:/WorkDir/USRealEstate/Source-Code/mls-common/src/main/java/com/ossez/usreio/mls/common/dao/factories/ListingMlsPhotoFactory.java: Some input files use unchecked or unsafe operations.
[INFO] /C:/WorkDir/USRealEstate/Source-Code/mls-common/src/main/java/com/ossez/usreio/mls/common/dao/factories/ListingMlsPhotoFactory.java: Recompile with -Xlint:unchecked for details.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.738 s
[INFO] Finished at: 2022-01-12T16:52:51-05:00
[INFO] ------------------------------------------------------------------------
PS C:\WorkDir\USRealEstate\Source-Code\mls-common> 

然后 Maven 将会在 target 文件夹中生成 Metamodel 的源代码。

生成的源代码如上图。