Saturday, February 09, 2008

Multiple Persistence Units with Spring and JPA

Recently I've been building an application with Spring, Hibernate and JPA. The application uses a single persistence unit with a number of entities stored in a single database schema.

Next I need to add some functionality that queries data from another database schema. I'd like to be able to implement this as a self-contained module packaged as a jar file that could be dropped into any application, not just the one I'm currently implementing. The module therefore needs to configure its own persistence unit and all supporting objects, namely a database connection pool and transaction manager. I don't need global transaction support since the module is only reading information from the second schema.

To meet these criteria, the jar file for the module needs to include:

  1. Annotated classes reponsible for executing queries using some combination of JPA and Hibernate APIs.
  2. JPA configuration file for defining the persistence unit
  3. Spring configuration file that declares beans for the database connection pool, entity manager factory and transaction manager and initializes the persistence unit.

Applications should be able to integrate the module in three steps:

  1. Add the jar file to the classpath
  2. Add the module's Spring configuration file to the list of files used to configure the application's Spring container.
  3. Define system properties to override the database connection information (url, user name, password) for the module

The Spring documentation has a brief section on dealing with multiple persistence units. The instructions there seemed relevant but the solution I ultimately came up with did not require defining my own PersistenceUnitManager. I'll explain the solution in my next post.

No comments: