Multiple persistence.xml files and spring
Today I struggled a bit with multiple persistence.xml files using Spring, JPA (duh).
I had two jar's each containing mapped domain objects and an associated persistence.xml file.
Unfortunately the JPA specification doesn't say anything about how to handle multiple persistence.xml files hence no merging is done by default.
Some searching led me to a jira issue concerning this that Juergen Hoeller have closed for spring 2.0.4.
We have just implemented our own PersistenceUnitManager capable of collecting multiple persistence.xml files and it works great!
Java code:
package com.foobar.spring;
public class MyPersistenceUnitManager extends DefaultPersistenceUnitManager {
protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
super.postProcessPersistenceUnitInfo(pui);
pui.addJarFileUrl(pui.getPersistenceUnitRootUrl());
MutablePersistenceUnitInfo oldPui = getPersistenceUnitInfo(pui.getPersistenceUnitName());
if (oldPui != null) {
List urls = oldPui.getJarFileUrls();
for (URL url : urls) {
pui.addJarFileUrl(url);
}
}
}
}
And in your spring configuration add the following (Most likely called applicationContext.xml):<bean id="persistenceUnitManager" class="com.foobar.spring.MyPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
...