Decouple a JPA entities jar from persistence.xml in SE environment

yannisf picture yannisf · Apr 12, 2010 · Viewed 9.8k times · Source

Is there a way to reuse a jar with JPA annotated entities in more than one SE applications (as a dependency)? <jar-file> in persistence.xml is not supported in SE environments so is there another way?

Answer

Pascal Thivent picture Pascal Thivent · Apr 12, 2010

Officially (per specification), you have to specify all classes using the class element. Quoting the chapter 6.2.1.6 mapping-file, jar-file, class, exclude-unlisted-classes of the JSR-220:

A list of named managed persistence classes may also be specified instead of, or in addition to, the JAR files and mapping files. Any mapping metadata annotations found on these classes will be processed, or they will be mapped using the mapping annotation defaults. The class element is used to list a managed persistence class. A list of all named managed persistence classes must be specified in Java SE environments to insure portability. Portable Java SE applications should not rely on the other mechanisms described here to specify the managed persistence classes of a persistence unit. Persistence providers may also require that the set of entity classes and classes that are to be managed must be fully enumerated in each of the persistence.xml files in Java SE environments.

Now, if you don't mind being not portable, Hibernate supports using the jar-file element in Java SE (in this case an absolute url is needed, not handy). Hibernate actually also supports auto-detection even in JSE. Much better:

<persistence 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"
  version="1.0">
  <persistence-unit name="foo">

    <!-- This is required to be spec compliant, Hibernate however supports auto-detection even in JSE. -->
    <class>foo.Bar<class>

    <properties>
      <!-- Scan for annotated classes and Hibernate mapping XML files -->
      <property name="hibernate.archive.autodetection" value="class, hbm"/>
      ...
    </properties>
  </persistence-unit>

</persistence>