Archive for the ‘Hibernate’ category

Starting out with Spring and Hibernate JPA

January 21st, 2010

More often than not, I am brought onto a project after the project initiation phase has been completed.  By this stage major decisions regarding the development environment and code organisation have already been made.  It would be fairly common that I would refactor and re-organise some of the code and in particular the Hibernate JPA code.

In this post I am going to outline how I prefer to implement and organise the Hibernate JPA code on projects I am involved with (where that option exists). I will also demonstrate how I implement the persistent entity classes, data access objects, associated configuration and unit tests.  A fairly typical project would utilise Maven, Spring and Hibernate JPA.

Creating the Maven Project

My preferred project structure consists of a root project containing a model module and persistence module with the persistence module having a dependency on the model module.  While this would seem pretty straight forward, one now has to decide if one is going to use annotations or  XML configuration for the ORM mapping.  The reason I prefer to make this decision now is that it affects the dependencies of the model module.

There are arguments for and against using annotations or XML for ORM (any XRM really) but if no precedent has been set I normally try to avoid using annotations in model classes.  This way model classes are very clean and the model module does not have any dependencies on javax.persistence.  I was involved in a project using JPA and JAXB annotations in model classes and they became difficult to work with very quickly.

The persistence module really does encapsulate all the information relating to the persistence mechanism with the exception of (some) transactional characteristics which would ordinarily be defined in service classes within a service module.  Of course the price you pay for this is having some quite large XML files.
» Read more: Starting out with Spring and Hibernate JPA