如何指示Maven忽略我的main/resources/persistence.xml以支持test/...?

yeg*_*256 16 java maven-2 openejb

persistence.xml为了测试,我有两个文件:

  • src/main/resources/META-INF/persistence.xml
  • src/test/resources/META-INF/persistence.xml

如何指示Maven在测试期间忽略第一个文件?现在它不会被忽视,因为OpenEJB说:

ERROR - FAIL ... Finder: @PersistenceContext unitName has multiple matches: 
unitName "abc" has 2 possible matches.
Run Code Online (Sandbox Code Playgroud)

Dav*_*ins 11

查看针对您尝试执行的操作的备用描述符功能.

试试这个设置:

  • src/main/resources/META-INF/persistence.xml
  • src/main/resources/META-INF/test.persistence.xml

然后,您可以test.persistence.xml通过将openejb.altdd.prefixSystem或InitialContext属性设置为来构造OpenEJB以优先选择该文件test

另一种可能的解决方案是覆盖测试中的持久性单元属性.通过这种方法,你可以避免需要一秒钟persistence.xml,因为保持两个可能是一个痛苦.

您可以使用Maven方法,但请注意,根据规范,持久性提供程序只会@Entity在找到的确切jar或目录中查找(也称扫描)bean persistence.xml.所以要敏锐地意识到,在Maven中,这是两个不同的位置:

  • target/classes
  • target/test-classes

编辑有关最重要功能的更多详细信息

您可以通过系统属性或初始上下文属性(包括jndi.properties文件)覆盖测试设置中的任何属性.格式为:

<unit-name>.<property>=<value>
Run Code Online (Sandbox Code Playgroud)

例如,如下所示persistence.xml:

<persistence>
  <persistence-unit name="movie-unit">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>movieDatabase</jta-data-source>
    <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>
    <properties>
      <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
    </properties>
  </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

您可以在测试用例中覆盖添加持久性单元属性.目前没有可以移除它们的设施(如果您有需要让我们知道 - 它到目前为止还没有真正出现).

Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

p.put("movie-unit.hibernate.hbm2ddl.auto", "update");
p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

context = new InitialContext(p);
Run Code Online (Sandbox Code Playgroud)

或者通过jndi.properties文件

java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory
movie-unit.hibernate.hbm2ddl.auto = update
movie-unit.hibernate.dialect = org.hibernate.dialect.HSQLDialect
Run Code Online (Sandbox Code Playgroud)

  • 是的,我正在使用Maven,严格分离生产`persistence.xml`和测试`persistence.xml`很重要.这就是为什么我强烈不同意将`test.persistence.xml`放入`src/main/resources`的想法. (4认同)