Simplified ORM configuration with Spring, JPA and Hibernate path scanning
By Lukas Stewart
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:
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:
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.
04 Oct 2013
Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.