Sandeep Rao
Sandeep Rao

Reputation: 1757

how to load a class from a jar file in persistence.xml file

How to load a model existing in a jar file to the persistence unit in ear application ?

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="PersonalizedOfferAssertionPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>java:/DefaultDS</non-jta-data-source>
        <jar-file>../../lib/test.jar</jar-file>
        <class>com.test.entity.Transaction</class>
    </persistence-unit>
</persistence>

Transaction class is in the test.jar file but I am getting class not found exception when trying to deploy the ear application.

Upvotes: 1

Views: 4594

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

From the book Pro JPA :

Any JAR listed in a jar-file entry must be on the classpath of the deployment unit....... Again, this may be done by either putting the JAR in the lib directory of the EAR (or WAR if you are deploying a WAR), adding the JAR to the manifest classpath of the deployment unit or by some other vendor-specific means. When listing a JAR in a jar-file element, it must be listed relative to the parent of the JAR file in which the META-INF/persistence.xml file is located.

This matches what you would put in the classpath entry in the manifest.

For example, assume the enterprise archive (EAR), that we will call emp.ear, is structured as shown in Listing 13-5.

Listing 13-5. Entities in an External JAR

emp.ear
emp-ejb.jar
META-INF/persistence.xml
lib/emp-classes.jar
examples/model/Employee.class

The contents of the persistence.xml file should be as shown in Listing 13-6, with the jar-file element containing “lib/emp-classes.jar” to reference the emp-classes.jar in the lib directory in the EAR file. This would cause the provider to add the annotated classes it found in emp-classes.jar (Employee.class) to the persistence unit, and because the jar is in the lib directory of the EAR, it would automatically be on the application classpath.

Listing 13-6. Contents of persistence.xml

<persistence-unit name="EmployeeService">
    <jta-data-source>java:app/jdbc/EmployeeDS</jta-data-source>
    <jar-file>lib/emp-classes.jar</jar-file>
</persistence-unit>

Upvotes: 3

Related Questions