We are developing a web application with Spring, Hibernate and Maven in a very modular fashion. There are core projects defining data access and view specific stuff, then there are modules defining logic and entities (@Entity
) and then there's the web app defining controller and view.
Now we have a security module defining security entities like account and role and we have a prototype module defining some example entities like customer and order. Both have a PersistenceUnit
defined inside a persistence.xml
which is pretty much empty except for the PersistenceUnit name, as all database configuration is done in the web app with a datasource.xml. The web app is supposed to load both jars as maven dependencies.
Both projects will build fine, autocscanning all entities and creating them for their respective unit tests. They will also get loaded inside the web app successfully if added individually.
However, as soon as both are loaded at the same time, the second one will override the PersistenceUnit
of the first one and thus create an IllegalArgumentException : Not an entity
for all entities from the first one. If both projects have a different persistence unit, loading the web app will throw another exception saying that no single default persistence unit
defined.
So.. how can I get all @Entity
annotated classes to load up in my web app without having to define them all inside the persistence.xml
(like here) but rather via component scan?
This seems like an idea, though I don't know how to use and test it...
I think we either have to merge all PersistenceUnits inside the web app or load all Entities programmatically. Defining them hard-coded inside the persistence.xml is not an option for us.
We use a similar module layout, but we place the persistence context in the war-part of our application and inject the entitymanager into the DAOs of the modules. Except for unit testing, the modules don't have a PU. We did this because we were afraid, that a transaction spanning multiple modules could cause trouble.
In the DAO
@PersistenceContext
private EntityManager em;
In the persistance.xml you need to enlist all entities with the elements.
<persistence-unit name="myPU">
<class>com.Entity1</class>
<class>com.Entity2</class>
etc.