JPA entities scanning in TomEE


JPA offers the ability to discover entities scanning the application classes instead of asking you to define all entities in the persistence unit. It is the effect of ‘exclude-unlisted-classes’ parameter.

For a simple application with a single persistence unit it is pretty nice but it means the container will scan your app for CDI, JSF, EJB…stuffs (in TomEE we already unified those parts – one of the reason why you shouldn’t use a plain old Tomcat if you use more than one of these technologies) then re-scan it for JPA (it is delegated to the JPA provider).

For big apps it can be a little pain to write/work on integration tests and moreover it uses more memory (scanning is not shared).

openejb.jpa.auto-scan or just let get it (almost) for free

Now in OpenEJB and TomEE you can add to your persistence.xml (persistence unit in fact) the property ‘openejb.jpa.auto-scan’ to your persistence unit properties. That’s a boolean which will ask OpenEJB to use all found @Entity classes, put them in the persistence unit and set ‘excluded-unlisted-classes’ to true. This way the JPA provider will not scan the app :).

Here is a sample:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
  <persistence-unit name="my-pu">
    <jta-data-source>foo</jta-data-source>
    <non-jta-data-source>bar</non-jta-data-source>
    <!-- no classes -->
    <properties>
      <property name="openejb.jpa.auto-scan" value="true"/>
      ...
    </properties>
  </persistence-unit>
</persistence>

Why this scanning is a free op? Because OpenEJB/TomEE scans classes then with this JPA config we simply reuse the result of the scanning so we can compare it to a get in a map :).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s