【问题标题】:JPA resources for test and production用于测试和生产的 JPA 资源
【发布时间】:2017-09-01 08:42:56
【问题描述】:

我有两个非常典型的基于 maven 的项目的持久性文件。

  • src/main/resources/persistence.xml (JNDI)
  • src/test/resources/persistence.xml (LOCAL_RESOURCE)

eclipse 和 maven 都无法在测试运行时向 junit 提供,但我的测试失败。

【问题讨论】:

  • 它应该在 META-INF 下,而不是在根目录下。
  • 失败的可能不是 Eclipse。其他人报告说使用 maven-failsafe-plugin 触发的测试不会将 target/test-classes 放在 target/classes 之前的类路径中,因为它应该覆盖 META-INF/persistence.xml (顺便说一句,它应该在 META-INF 中,而不是资源根目录)。我使用 maven-surefire-plugin 运行测试并加载了正确的 persistence.xml
  • 如何加载您的 persistence.xml 文件?通过类路径?

标签: eclipse maven jpa


【解决方案1】:

作为最后的手段,尝试使用maven-resources-plugin 强制复制:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
        <executions>
          <execution>
            <id>copy-resources</id>
            <!-- here the phase you need -->
            <phase>validate</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}</outputDirectory>
              <resources>          
                <resource>
                  <directory>src/**/*.xml/directory>
                  <filtering>true</filtering>
                </resource>
              </resources>              
            </configuration>            
          </execution>
        </executions>
      </plugin>
    </plugins>
    ...
  </build>
  ...
</project>

未测试。

【讨论】:

    【解决方案2】:

    正如我在评论中解释的那样,我相信问题出在 maven 插件上。如果可能的话,请尝试使用 maven-surefire-plugin 而不是 maven-failsafe-plugin。但是,即使您让它与第二个persistence.xml 一起工作,在维护方面也会遇到不同的问题(至少在 Hibernate 5.2 中)。它不会从主要来源检测带注释的类,而只会从测试中检测到,您必须使用&lt;class&gt; 标签列出它们,并且尽量不要忘记每次都这样做。我发现对我有用的解决方案是只有主 xml 并像这样实例化我的EntityManagerFactory

    @BeforeClass
    public static void initJpa() throws Exception {
        TreeMap<String, Object> props = new TreeMap<>();
        props.put("javax.persistence.jdbc.driver", "org.postgresql.Driver");
        props.put("javax.persistence.jdbc.url", "jdbc:postgresql://127.0.0.1:5432/projectdb");
        props.put("javax.persistence.jdbc.user", "testuser");
        props.put("javax.persistence.jdbc.password", "testpass");
        props.put("javax.persistence.nonJtaDataSource", null); // important to override the data-source!
        emf = Persistence.createEntityManagerFactory("persistance.unit.name", props);
    }
    

    javax.persistence.nonJtaDataSource 属性最终起到了作用。

    这应该会绕过您遇到的类加载覆盖问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 2017-11-12
      • 2012-11-10
      • 2017-01-05
      相关资源
      最近更新 更多