Simplified ORM configuration with Spring, JPA and Hibernate path scanning

Configuring Spring, JPA, Hibernate or other ORM technologies can be a challenge. One way to simplify ORM configuration is to configure package scanning for entity classes.

A challenge when developing applications that use object-relational mapping (ORM), a common approach is to list each @Entity decorated Java class programmatically either in the configuration file or within the class that creates the ORM session. However, ORM configuration can be simplified by using a common feature known as package scanning.

Standard JPA configuration

A typical configuration file might look something like this, which isn't too bad with only three entities, but it's not difficult to imagine the configuration getting extensive.


Simplified JPA and Hibernate configurations

One option available using JPA is to scan JAR files for entities using the sensibly named jar-file entry:


Configuring Spring

Of course, the best configuration is one that does complete scanning. This can be achieved by setting the exclude-unlisted-classes JPA entry to false in standard Java EE applications. And it's just as easy, if not easier when using Spring. With Spring, configuration file can be edited with the following entry to force package scanning of @Entity decorated classes, rather than forcing a listing of all classes:

<bean id="entityManager" 
  p:packagesToScan="com.theserverside.entities" />

In this example, any classes in the com.theserverside.entities package will be found and managed at runtime by the ORM container.

There is of course always the potential that an entity will end up being created outside of a listed package, and ORM problems will be encountered at testing, but by using the package or JAR scanning features, developers greatly reduce the number of times they need to edit ORM configuration files.

This was last published in October 2013



Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: