Support for Multiple Persistence Units with JPA

DZone 's Guide to

Support for Multiple Persistence Units with JPA

· Java Zone ·
Free Resource

Overall, JPA is pretty great. When it first showed up on the scene, a bunch of us realized that the handling of the persistence units through an XML config file in META-INF had a huge downside: you had to list all the entities you were going to use wherever you were going to use them. So, naturally, if you have domain classes in a jar file and are then going to diddle them in a war file, you would have to relist all of them in two places. Yup, that‘s right, this violates the most basic grade K principle: DRY.

Solutions varied. We looked around for scanners, and when we didn‘t find one, we wrote one, in conjunction with the Spring classes. Problem was, we had to point to the jars we were going to use, then we would go gather them up and hand them over to the Spring Entity Gestapo. Well, this solution sucked for a number of reasons (seems like I spend a lot of time enumerating various forms of suckiness):

  1. Listing the jars meant you had an explicit reference to a specific file, which of course implies a version, so there is maintenance.
  2. This also violates DRY because we have already told the build gestapo (Maven) about these same items.
  3. Now, here‘s where the suck kicks into turbo mode: the jars have to be in target, so we thought we would make a simple maven goal to copy them there, but since there is no way to hook custom goals inside eclipse, using m2Eclipse, we ended up with a situation where you would go to build the project and it would fail, and you‘d hit yerself on the forehead like the idiots who don‘t like vegetable juice, and remember ‘der, I have to run a Maven goal from the command line once to get these files copied.‘
  4. Finally, even with the copying, there were sometimes when the versions did not match up so the file got copied, but it was slightly different.

After slipping into the snare of #4 again last week, I decided it was time to blow up the old scanner. The solution had to be found on the classpath. All things considered, changing to this approach was not that bad. Of course, it‘s mostly for running tests that you have problems, but we quickly figured out that the test classpath had paths inside to all the required jars sitting in the maven repo so we just go there and look for them.

You still have to specify the jars you want added, but you can just use simple names and the scanner will find that jar on the classpath. Here is a sample Spring config:

If this is of any interest, download the code from here.

From http://www.jroller.com/robwilliams


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}