Chapter 7 - Persistence Units and Persistence Contexts
A persistence unit is an set of all entity classes that are managed by EntityManager instances in an application. This set of entity classes represents the data contained within a single data store.
Persistence units are defined by the persistence.xml configuration file. The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
Persistent units can be packaged as part of a WAR or EJB JAR file, or can be packaged as a JAR file that can be included in an WAR or EAR file.
If package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
If package the persistence unit in a JAR file that will be included in a WAR or EAR file, the JAR file should be located:
• In the WEB-INF/lib directory of a WAR.
• In the top-level of an EAR file.
• In the EAR file’s library directory.
The persistence.xml File
persistence.xml defines one or more persistence units.
< persistence-unit name="OrderManagement" >
< description > This unit manages orders and customers.
It does used for vendor-specific features and can
therefore be deployed to any persistence provider.
< /description >
< jta-data-source > jdbc/MyOrderDB < /jta-data-source >
< jar-file > MyOrderApp.jar < /jar-file >
< class > com.widgets.Order < /class >
< class > com.widgets.Customer < /class >
< /persistence-unit >
< /persistence >
This file defines a persistence unit named OrderManagement, which uses a JTA-aware data source jdbc/MyOrderDB.
The jar-file and class elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses.
The jar-file element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while the class element explicitly names managed persistence classes.
The transactional type of the entity manager, transactions involving EntityManager operations may be controlled either through JTA or through use of the resource-local EntityTransaction API, which is mapped to a resource transaction over the resource entity manager.
An entity manager is defined to be of a given transactional type - either JTA or resource-local - at the time its underlying entity manager factory is configured and created.
Persistence Units in java