有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Hibernate JPA 2元模型生成器?

当我根据http://docs.jboss.org/hibernate/stable/jpamodelgen/reference/en-US/html_single/学习Hibernate JPA 2元模型生成器时,它工作正常
但当我试图通过运行mvn compile来生成这些元模型时,它只在目标文件夹中生成了相应的类和一个奇怪的文件夹“generated sources”,如下所示,而没有在源文件夹中生成相应的java文件。 enter image description here

下面是我在pom中的相关配置。xml:

    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerArgument>-proc:none</compilerArgument>
    </configuration>
</plugin>
<plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <version>3.2.0</version>
    <executions>
        <execution>
                <id>process</id>
            <goals>
                <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <processors>
                    <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                </processors>
            </configuration>
        </execution>
    </executions>
</plugin>
</plugins>


所以,我的问题是:这是预期的行为吗?如果是,是否意味着每次使用元模型之前都需要编译代码?。如果没有,如何在源代码文件夹中生成java文件

提前感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    But when I tried to generate these metamodel by run mvn compile, it only generated corresponding classes and a strange folder 'generated-sources' in target folder as below and does not generated corresponding java files in source folder.

    生成的元类的默认文件夹是${project.build.directory}/generated-sources/apt,其中${project.build.directory}默认为target。所以生成的元类应该在target/generated-sources/apt目录下(正如我从你的截图中猜到的,元类是生成的)

    如果要更改此行为,可以使用outputDirectory元素将插件配置为生成另一个文件夹中的元类,如下所示:

    <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
            <execution>
                <id>process</id>
            <goals>
                <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <processors>
                    <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                </processors>
                 <outputDirectory>${project.basedir}/generated</outputDirectory>
            </configuration>
        </execution>
    </executions>
    

    不要忘记将新文件夹添加到类路径中,否则项目可能无法生成

    is this expected behavior?

    If yes, does it mean that I need to compile code before I use metamodel each time?

    是的,但如果不更改或添加新实体,则可以使用generaed类,前提是至少运行一次mvn compile

    If no, how can I generate java files in source code folder?

    我不建议这样做:-)我的意思是,将生成的类与源代码混合不是一个好主意。如果您不喜欢target文件夹,请使用上述任何其他文件夹