Java - JPA - Why do we need multiple <persistence-unit> tags in persistence.xml?
I am studying JPA. I read about persistence.xml file. It can contain more than one <persistence-unit> tag in the <persistence> .
In my absence, <persistence-unit> defines:
- Db connection settings
- classes (entity classes), jar files, and mapping files
- provider information
Then why do we need to group the objects of our application into different <persistence-unit> . All objects of any application must be in the same <persistence-unit> .
The only reason it seems to me that we need more than one <persistence-unit> is when we need to establish a connection to several data stores.
Q1. Are there other situations where we need more than one <persistence-unit> ?
A storage unit is a data warehouse. Your question has a bit of a smell that you expect that you can have more than one data store for exactly the same data. It makes no sense. The way <persistence-unit> works makes sense. Definition of parameters for connecting to the database, object mappings, etc. For a unique and independent data warehouse. You can add more, but they will be completely independent of each other. If you want or want to link several data warehouses with each other, then the solution should be sought at a lower level, namely in the data warehouse itself.
I think you answered your question:
The only reason it seems to me that we need more than one is when we need to establish a connection to several data stores.
Configuration files, in this case persistence.xml, should be flexible and unambiguous. If you can omit the tag if there is only one persistence unit, you introduce unnecessary ambiguity. In addition, it introduces complexity when validating XML schemas.
I use it to test JUnit. I have another data source for my hsqldb memory and my actual application data store. The only caveat is that I must explicitly state the 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;