Sharing a Persistence Unit Across Components in a .Ear File

Configure persistence units to be available in several jars of an ear

As per the JPA spec, it should be possible for you to define a persistence unit at the EAR level that is visible to all the submodules that you define in the same .ear:

8.2.2 Persistence Unit Scope

...

A persistence unit that is defined at the level of the EAR is
generally visible to all components in the application
. However, if a
persistence unit of the same name is defined by an EJB-JAR, WAR, or
application jar file within the EAR, the persistence unit of that name
defined at EAR level will not be visible to the components defined by
that EJB-JAR, WAR, or application jar file unless the persistence unit
reference uses the persistence unit name # syntax to specify a path
name to disambiguate the reference.

However, in section 8:

NOTE: Java Persistence 1.0 supported use of a jar file in the root of
the EAR as the root of a persistence unit. This use is no longer
supported. Portable applications should use the EAR library directory
for this case instead
. See [9].

So I would try to place the jar in the lib folder. If you need that module to be a EJB one, it must be in the root of the ear, so you can create a separate jar with the persistence.xml file.

Entity unknown in EAR with persistence unit in another jar

According to the directory structure you posted the jars entity.jar and resource.jar are in the same directory: lib. So the jar-file entry in the persistence.xml file should be:

<jar-file>entity.jar</jar-file>

istead of

<jar-file>../entity.jar</jar-file>

With the persistence archive (the jar containing persistence.xml under META-INF directory) in the lib directory of the ear file, the persistence unit myPU should be visible to all components in the ear. And here is a slightly modified directory layout:

EAR
moduleEjb.jar
moduleWeb.war
lib
entity.jar
resource.jar
META-INF // in the root of the jar file
persistence.xml

Related reading: Chapter 8: Entity Packaging of JPA 2.1 specification.

Two Persistence Unit in one Persistence.xml

The problem is that the JPA does not know which is the persistence unit to use. when you have only one persistence unit this problem does not occur. To fix do the following:

You need to specify a persistence unit : @PersistenceContext(unitName="...") in the Ejb that do not have



Related Topics



Leave a reply



Submit