开发者

Different persistence.xml properies for test run / JPA Fixtures

I develop some Java EE/Spring web-app. I use JPA 2.0 - Hibernate. For integration tests I need to use different database. Those tests require Jetty to run application, but I managed to override web.xml for such run, there I can modify my Spring context files, it's ok. But I need each time a clean database (and load some data into it). As my database name and address are configured in sprig context I just switched them as I described above - but how can I change some of my persistence.xml properies for this tests only to have database drop and recreated? I tried to make another persistence.xml in /src/test/resources/META-INF (and checked that test-classes are first in classpath) but it i开发者_如何学编程s not loaded and only the 'master' version is used (from /src/main/resources/META-INF). Any help?


With spring you usually define your data source as a spring bean. The database url and credentials are usually included form an external file, for example application.properties.

If you put a new applicaiton.properties in src/test/resources it will work. See also here.


You can define org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager :

<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
       <property name="persistenceXmlLocations">
         <list>
           <value>/path/to/my/test-persistence.xml</value>
         </list>
       </property>
       <property name="dataSources">
         <map>
           <entry key="dataSource" value-ref="dataSource"/>
         </map>
       </property>
       <!-- if no datasource is specified, use this one -->
       <property name="defaultDataSource" ref="dataSource"/>
    </bean>

Then, link it to your entityManagerFactory :

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    ...
    ...
    <property name="persistenceUnitManager" ref="pum"/>
</bean>

I used this to make my own persistence.xml linked to a HSQL in-memory db, preloaded with DBUnit (using hibernate.hbm2ddl.auto=create-drop).

It Works perfectly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜