My persistence.xml
has 2 persistence-units. Each of them has several <class>
elements.
I thought that we must specify all classes related to certain persistence-unit. But I accidentally forgot to specify class-element for new entity but the program worked fine even without it. Then I removed all class-elements and everything worked fine. So, why do we need it?
sample code:
<persistence-unit name="JiraManager" transaction-type="RESOURCE_LOCAL">
<class>chartdemo.model.domain.Category</class>
</persistence-unit>
You only need a persistence element as the root element and a persistence-unit element with a name attribute. The attribute is used to identify the persistence unit, and you can use it during the bootstrapping process to instantiate a specific EntityManagerFactory.
The Persistence Unit defines all the metadata required to bootstrap an EntityManagerFactory, like entity mappings, data source, and transaction settings, as well as JPA provider configuration properties. The goal of the EntityManagerFactory is used to create EntityManager objects we can for entity state transitions.
A list of all named managed persistence classes must be specified in Java SE environments to insure portability If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element should be used.
You can not only add classes to your persistence-unit which are not at its root, you can also exclude classes which would be added by default. To do that, you first need to use one or more class elements to explicitly specify which managed classes shall be part of the persistence-unit.
If you didn't specify classes in the persistence.xml
file your persistence manager will manage all entity classes in location where persistence.xml file exists (jar file, class directory).
Listing classes gives you flexibility to choose entities and group them in persistence unit. You can have finer control what consist a given persistent unit name - you can also include entites from other jars etc.
So, in most basic cases listing classes is unnecessary, and most of JPA impementations discover all entities for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With