开发者

Java - JPA - Why we need more than one <persistence-unit> tag in persistence.xml file?

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 t开发者_如何学编程han 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?


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.


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜