Подтвердить что ты не робот

Eclipselink 2.5 Генерация метамодели с использованием Maven

Я хотел бы знать, как создавать статические метамодели с использованием Maven и Eclipselink 2.5. Он отлично работал, добавив эти строки в pom.xml при запуске Eclipselink 2.4.

// Generate meta model for eclipselink 2.4 (does not work for 2.5)
    <plugin>
                    <groupId>org.bsc.maven</groupId>
                    <artifactId>maven-processor-plugin</artifactId>
                    <version>1.3.1</version>
                    <executions>
                        <execution>
                            <id>process</id>
                            <goals>
                                <goal>process</goal>
                            </goals>
                            <phase>generate-sources</phase>
                            <configuration>
                                <compilerArguments>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</compilerArguments>
                                <processors>
                                    <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
                                </processors>
                                <outputDirectory>${project.build.directory}/generated-sources/meta-model</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

Но, похоже, что-то изменилось с 2.4, потому что я получаю следующую ошибку:

[INFO] javac option: -proc:only
[INFO] javac option: -Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml
[INFO] javac option: -processor
[INFO] javac option: org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
[INFO] javac option: -s
[INFO] javac option: /home/asdf/target/generated-sources/meta-model
[INFO] diagnostic error: Annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' not found
[INFO] diagnostic warning: Annotation processing without compilation requested but no processors were found.
[ERROR] execute error
java.lang.Exception: error during compilation
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.executeWithExceptionsHandled(AbstractAnnotationProcessorMojo.java:183)
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.execute(AbstractAnnotationProcessorMojo.java:96)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

Можете ли вы, ребята, помочь мне? =)

B.R

4b9b3361

Ответ 1

Похоже, что они переместили класс CanonicalModelProcessor в свой собственный артефакт maven:

<dependency>
  <groupId>org.eclipse.persistence</groupId>
  <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
  <version>2.5.0</version>
</dependency>

Для меня работает следующая конфигурация maven-processor-plugin:

        <plugin>
            <groupId>org.bsc.maven</groupId>
            <artifactId>maven-processor-plugin</artifactId>
            <version>2.2.4</version>
            <executions>
                <execution>
                    <id>eclipselink-jpa-metamodel</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>
                        <processors>
                            <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
                        </processors>
                        <outputDirectory>${project.build.directory}/generated-sources/meta-model</outputDirectory>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.5.0</version>
                    <scope>provided</scope>
                </dependency>
            </dependencies>
        </plugin>

Очень важно отметить: метамодель генерируется только в том случае, если сущности объявлены в модуле сохранения. Он не работает с обнаруженными объектами.

Ответ 2

Чтобы сделать конфигурацию намного проще, я бы рекомендовал вам протестировать: https://github.com/ethlo/eclipselink-maven-plugin. Вам даже не потребуется хранить обновленный файл persistence.xml.

<plugin>
<groupId>com.ethlo.persistence.tools</groupId>
<artifactId>eclipselink-maven-plugin</artifactId>
<version>[version]</version>
<executions>
    <execution>
        <id>weave</id>
        <phase>process-classes</phase>
        <goals>
            <goal>weave</goal>
        </goals>
    </execution>
    <execution>
        <id>modelgen</id>
        <phase>generate-sources</phase>
        <goals>
            <goal>modelgen</goal>
        </goals>
    </execution>
</executions>
</plugin>

Примечание. Я автор плагина.

Ответ 3

Для использования maven-compiler-plugin из org.apache.maven.plugins в MojoFailureException при использовании другой команды используется mvn clean install.

Проверены решения с org.eclipse.persistence.jpa.modelgen.processor 2.6.0.

Конфигурация в обоих случаях очень похожа.

Основной проблемой, с которой я столкнулся с org.bsc.maven, была правильная настройка частей compilerArguments. Вот почему я публикую (оба) решения ниже.

Документация доступна: ЗДЕСЬ.


Решение с использованием maven-compiler-plugin от org.bsc.maven

Для меня это работало лучше

<plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <executions>
        <execution>
            <id>eclipselink-jpa-metamodel</id>
            <goals>
                <goal>process</goal>
            </goals>
            <configuration>
                <compilerArguments>
                    -Aeclipselink.persistencexml=${basedir}/src/main/resources/META-INF/persistence.xml
                </compilerArguments>
                <processors>
                    <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
                    </processor>
                </processors>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${eclipselink.version}</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</plugin>

Решение с использованием maven-compiler-plugin от org.apache.maven.plugins

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
    <version>${eclipselink.version}</version>
    <scope>compile</scope>
</dependency>

...

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArgs>
            <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
        </compilerArgs>
    </configuration>
</plugin>

Ответ 4

вы, вероятно, получите следующую ошибку:

java.lang.RuntimeException: java.lang.SecurityException: class "org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProperties" signer information does not match signer information of other classes in the same package

Из-за неустановленной ошибки компиляция нарушена, файл-jar подписан в maven-репозитории, версия должна быть установлена ​​в 2.5.0-SNAPSHOT пока.

Ответ 5

2017 ОБНОВЛЕНИЕ:

Главный ответ на этот вопрос теперь устарел. Теперь вам нужно выполнить следующие шаги, чтобы он работал.

1) Импортируйте требуемую зависимость:

<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.jpa.modelgen.processor -->
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
    <version>2.5.2</version>
    <scope>compile</scope>
</dependency>

2) Укажите местоположение persistence.xml(это обходной путь для ошибки EL. Обратите внимание, что ваш путь может отличаться от указанного в этом примере):

<build>
  <pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <executions>
                <execution>
                    <id>default-compile</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
                [...]
            </executions>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <compilerArgs>
                    <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
                </compilerArgs>
            </configuration>
    </plugins>
    [...]
  </pluginManagement>
  [...]
</build>

3) Наконец, обратитесь к следующему элементу, чтобы инициировать выполнение с помощью Maven: Использование модуля maven Build Helper Maven

Ответ 6

UPDATE

Пожалуйста, просмотрите эту запись в блоге. И (Или) этот репозиторий. Я буду продолжать обновлять как запись, так и репозиторий.

Пожалуйста, уведомите меня любым способом, если необходимо внести какие-либо изменения.

Hibernate

Рекомендуется использовать Hibernate.

<plugin>
  <groupId>org.bsc.maven</groupId>
  <artifactId>maven-processor-plugin</artifactId>
  <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>
  <dependencies>
    <dependency>        
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>4.3.4.Final</version>
    </dependency>
  </dependencies>
</plugin>

OpenJPA

OpenJPA, похоже, требует дополнительного элемента <openjpa.metamodel>true<openjpa.metamodel>.

<plugin>
  <groupId>org.bsc.maven</groupId>
  <artifactId>maven-processor-plugin</artifactId>
  <executions>
    <execution>
      <id>process</id>
      <goals>
        <goal>process</goal>
      </goals>
      <phase>generate-sources</phase>
      <configuration>
        <processors>
            <processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
        </processors>
        <optionMap>
          <openjpa.metamodel>true</openjpa.metamodel>
        </optionMap>
      </configuration>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <version>2.3.0</version>
    </dependency>
  </dependencies>
</plugin>

EclipseLink

EclipseLink, как упоминал @dschoorl, требует persistence.xml с указанным <class/> в нем.

<plugin>
  <groupId>org.bsc.maven</groupId>
  <artifactId>maven-processor-plugin</artifactId>
  <executions>
    <execution>
      <id>process</id>
      <goals>
        <goal>process</goal>
      </goals>
      <phase>generate-sources</phase>
      <configuration>
        <processors>
          <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
        </processors>
      </configuration>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
      <version>2.5.1</version>
    </dependency>
  </dependencies>
</plugin>

Ответ 7

Это то, что я использовал

<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>javax.persistence</artifactId>
        <version>2.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.1</version>
            <scope>provided</scope>
        </dependency>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
            <executions>
                <execution>
                    <id>generate-entity-metamodel</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>
                            compile
                        </goal>
                    </goals>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <optimize>true</optimize>
                        <showDeprecation>true</showDeprecation>
                        <showWarnings>true</showWarnings>
                        <proc>only</proc>
                        <!--<compilerArgument>-Aeclipselink.metamodel=true</compilerArgument>
                        <generatedSourcesDirectory>${basedir}/src/main/java</generatedSourcesDirectory>-->
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>1.8</version>
            <executions>
                <execution>
                    <id>add-modelgen-generated-sources-directory</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>add-source</goal>
                    </goals>
                    <configuration>
                        <sources>
                            <source>${project.build.directory}/target/generated-sources/annotations</source>
                        </sources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

часть дополнительных ресурсов предназначена для netbeans 8, чтобы понять ее, чтобы поместить ее в classpath :)