Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to specify class inside <persistence-unit> element?

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>
like image 744
Roman Avatar asked Jan 04 '10 12:01

Roman


People also ask

Do I need a persistence element?

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.

What is the purpose of the persistence unit?

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.

What should be included in a list of Managed Persistence classes?

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.

How do I add classes to a persistence-unit?

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.


1 Answers

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.

like image 137
cetnar Avatar answered Sep 19 '22 09:09

cetnar