4

I am learning JPA. I read about persistence.xml file. It can contain more that one <persistence-unit> tag under <persistence> tag.

Upto my undestanding, <persistence-unit> defines:

  • db connection settings
  • classes(entity classes), jar files, and mapping files
  • provider information

Then why would we need to group the entities of our application into different <persistence-unit>. All the entities of any application should be in one <persistence-unit> tag.

The only reason that I think that we need more than one <persistence-unit> is when we need to establish connection with more than one datastore.

Q1. Are there any other situations when we need more than one <persistence-unit> tag?

3 Answers 3

4

A persistence unit represents a datastore. Your question has a bit the smell that you expect that you can have more than one datastore for exactly the same data. This makes no sense. The way the <persistence-unit> works makes perfectly sense. Defining the DB connection settings, the entity mappings, etc for an unique and independent datastore. You can add more, but they would be fully independent from each other. If you'd like or expect to link multiple datastores with each other, then the solution should be sought at a lower level, namely in the datastore itself.

2
  • If I need an application that transfers data from one datastore to another, then in that case we need to define two datastores(<persistence-unit>) for the same data.
    – Amit
    Commented Apr 6, 2010 at 17:25
  • 2
    Then you're doing the data transfer job at the wrong place using the wrong tools. Check if the DB offers sync/backup tools for this and make use of it.
    – BalusC
    Commented Apr 6, 2010 at 18:23
2

I think you have answered your own question:

The only reason that I think that we need more than one is when we need to establish connection with more than one datastore.

Configuration files, in this case persistence.xml, should be flexible and unambiguous. If you could ommit tag in case of having only one persistence unit, you introduce unnecessary ambiguity. Plus, it introduces complexity in XML schema verification.

0

I use it for JUnit testing. I have a different data source for my in memory hsqldb and my actual application data store. The only caveat is I have to explicitly state the perstitence unit name in the code

/**
 * Injected entity manager factory. Do not instantiate {@link EntityManager}
 * at a class level.
 */
@PersistenceUnit(unitName = "default")
private transient EntityManagerFactory emf;

Not the answer you're looking for? Browse other questions tagged or ask your own question.