How to instruct Maven to ignore my main/resources/persistence.xml in favor of test/…?

前端 未结 4 580
庸人自扰
庸人自扰 2021-02-07 08:28

I have two persistence.xml files, for the sake of testing:

  • src/main/resources/META-INF/persistence.xml
  • src/test/resources/
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 09:32

    Check out the alternate descriptors functionality which is aimed at what you're trying to do.

    Try this setup:

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

    Then you can construct OpenEJB to prefer the test.persistence.xml file by setting the openejb.altdd.prefix System or InitialContext property to test

    A different possible solution could be to override the persistence unit properties in the test. With that approach you could avoid the need for a second persistence.xml which can be nice as maintaining two can be a pain.

    You can use the Maven approach, but be aware that per spec the persistence provider will only look (aka scan) for @Entity beans in the exact jar or directory where the persistence.xml is found. So be keenly aware that in Maven these are two different locations:

    • target/classes
    • target/test-classes

    EDIT More details on the overriding capabilities

    You can override any property in your test setup via either system properties or the initial context properties (this includes jndi.properties files). The format is:

    .=
    

    So for example with the following persistence.xml:

    
      
        org.hibernate.ejb.HibernatePersistence
        movieDatabase
        movieDatabaseUnmanaged
        
          
          
        
      
    
    

    You can override and add persistence unit properties in your test case. There are currently no facilities for removing them (if you have a need for that let us know – it hasn't really come up so far).

    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);
    

    Or alternatively via a jndi.properties file

    java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory
    movie-unit.hibernate.hbm2ddl.auto = update
    movie-unit.hibernate.dialect = org.hibernate.dialect.HSQLDialect
    

提交回复
热议问题