The Persistence Layer with Spring Data JPA

Last Update: 13.04.2013 (2nd update)

Table of Contents

1. Overview

This article will focus on the configuration and implementation of the persistence layer with Spring 3.1, JPA and Spring Data. For a step by step introduction about setting up the Spring context using Java based configuration and the basic Maven pom for the project, see this article.

2. No More DAO implementations

As discussed in an earlier article, the DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many fold: a decrease in the number of artifacts that need to be defined and maintained, simplification and consistency of data access patterns and consistency of configuration.

Spring Data takes this simplification one step forward and makes it possible to remove the DAO implementations entirely – the interface of the DAO is now the only artifact that need to be explicitly defined.

3. The Spring Data managed DAO

In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface - JpaRepository – in Spring’s interface hierarchy. This will enable Spring Data to find this interface and automatically create an implementation for it.

Also, by extending the interface we get most if not all relevant CRUD generic methods for standard data access available in the DAO.

4. Defining custom access method and queries

As discussed, by implementing one of the Repository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented. To define more specific access methods, Spring JPA supports quite a few options – you can either simply define a new method in the interface, or you can provide the actual JPQ query by using the @Query annotation.

A third option to define custom queries is to make use of JPA Named Queries, but this has the disadvantage that it either involves XML or burdening the domain class with the queries.

In addition to these, Spring Data introduces a more flexible and convenient API, similar to the JPA Criteria API, only more readable and reusable. The advantages of this API will become more pronounced when dealing with a large number of fixed queries that could potentially be more concisely expressed through a smaller number of reusable blocks that keep occurring in different combinations.

4.1. Automatic Custom Queries

When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method name. While this has limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort.

For example, if the managed entity has a name field (and the Java Bean standard getter and setter for that field), defining the findByName method in the DAO interface will automatically generate the correct query:

public interface IFooDAO extends JpaRepository< Foo, Long >{

   Foo findByName( final String name );


This is a relatively simple example; a much larger set of keywords is supported by query creation mechanism.

In the case that the parser cannot match the property with the domain object field, the following exception is thrown:

java.lang.IllegalArgumentException: No property nam found for type class

4.2. Manual Custom Queries

In addition to deriving the query from the method name, a custom query can be manually specified with the method level @Query annotation.

For even more fine grained control over the creation of queries, such as using named parameters or modifying existing queries, the reference is a good place to start.

5. Spring Data transaction configuration

The actual implementation of the Spring Data managed DAO – SimpleJpaRepository – uses annotations to define and configure transactions. A read only @Transactional annotation is used at the class level, which is then overridden for the non read-only methods. The rest of the transaction semantics are default, but these can be easily overridden manually per method.

5.1. Exception Translation without the template

One of the responsibilities of Spring ORM templates (JpaTemplate, HibernateTemplate) is exception translation – translating JPA exceptions – which tie the API to JPA – to Spring’s DataAccessException hierarchy.

Without the template to do that, exception translation can still be enabled by annotating the DAOs with the @Repository annotation. That, coupled with a Spring bean postprocessor will advice all @Repository beans with all the implementations of PersistenceExceptionTranslator found in the Container – to provide exception translation without using the template.

The fact that exception translation is indeed active can easily be verified with an integration test:

@Test( expected = DataAccessException.class )
public void whenAUniqueConstraintIsBroken_thenSpringSpecificExceptionIsThrown(){
   String name = "randomName"; new Foo( name ) ); new Foo( name ) );

Exception translation is done through proxies; in order for Spring to be able to create proxies around the DAO classes, these must not be declared final.

6. Spring Data Configuration

To activate the Spring JPA repository support, the jpa namespace is defined and used to specify the package where to DAO interfaces are located:

<?xml version="1.0" encoding="UTF-8"?>

<jpa:repositories base-package="" />


At this point, there is no equivalent Java based configuration – support for it is however in the works.

7. The Spring Java or XML configuration

The previous article of the series already discussed in great detail how to configure JPA in Spring 3. Spring Data also takes advantage of the Spring support for the JPA @PersistenceContext annotation which it uses to wire the EntityManager into the Spring factory bean responsible with creating the actual DAO implementations – JpaRepositoryFactoryBean.

In addition to the already discussed configuration, there is one last missing piece – including the Spring Data XML configuration in the overall persistence configuration:

@ImportResource( "classpath*:*springDataConfig.xml" )
public class PersistenceJPAConfig{

8. The Maven configuration

In addition to the Maven configuration for JPA defined in a previous article, the spring-data-jpa dependency is added:


9. Conclusion

This article covered the configuration and implementation of the persistence layer with Spring 3.1, JPA 2 and Spring JPA (part of the Spring Data umbrella project), using both XML and Java based configuration. The various method of defining more advanced custom queries are discussed, as well as configuration with the new jpa namespace and transactional semantics. The final result is a new and elegant take on data access with Spring, with almost no actual implementation work.

You can check out the full implementation in the github project.

I usually post about Persistence on Google+ - you can follow me there:

Free eBook - REST Services with Spring
Join more than 2,200 engineers!

, ,

  • Pingback: Simple JPA Application with Hibernate « Zeeshan Akhter

  • sillystuff01

    Why is it a problem to “burden” the domain class with queries? The queries must live some where. The domain class seems as good a place as any for these queries.

    Also, the idea that I must use Spring to simplify my JPA raises red flags. Spring is not simple. Spring is huge, sprawling, and gets bigger and more invasive with each new version. Spring is poorly documented (maybe on purpose, to encourage support contracts) and full of unexplained magic.

    The success of L/Unix is based on keeping things simple. Spring is not simple. JPA is not simple. Mixing Spring and JPA adds layers of hidden, undocumented interactions that must be discovered, understood, and remembered.

    When you read the article above, it sounds suspiciously like the Microsoft lock-in approach: “embrace and extend”. Spring embraces JPA, but then adds a new layer on top that supposedly makes JPA easier. Well, now you need to know Spring’s wrapper, JPA, and your JPA implementation (probably Hibernate). Plus, you’re locked into Spring.

    In my opinion, it’s better to minimize dependencies between JPA and Spring. Keeping JPA separate also make unit testing simpler. Unit testing with Spring is much more involved.

    • Oliver Gierke

      As you seem to have a strong opinion (not arguments) about Spring and JPA, I’ll leave that part to you. Spring Data JPA is about you getting rid of the code to write which is more or less obvious. And as always, it’s a trade-off. You choose Spring because it gives you some benefits but to honestly work with it you need to understand it’s concepts. Welcome to the world of technology, a world where you need to understand what’s going on. Would anyone reasonably argue you don’t have to be aware of SQL and the traits of relational database just because you work with Hibernate? And yet it helps thousands of developers getting rid of all the manually written OR-Mapping code they would have had to write themselves mostly becoming as complex to understand as it would be to understand the relevant parts of Hibernate.

      > Spring is huge, sprawling, and gets bigger and more invasive with each new version.

      I don’t want to open up a general Spring discussion here but opinion doesn’t get more convincing by stating as little arguments as possible.

  • Murray B

    I’ve been waiting for this kind of technology for a long time – it works well and reduces a lot of time traditionally wasted writing CRUD DAOs. From a maintenance perspective I’m a big fan of having a single set of packages where you put your SQL rather than spread throughout the code so it’s easy to refactor, and this kind of lightweight framework simplicity makes it even easier to see what’s CRUD and what’s unique. Nice article, thanks!

  • Matt Trousdale

    I agree with guest “Why is it a problem to “burden” the domain class with queries?” There are a lot of shortfalls with Srping JPA some are dangerous when using hibernate. Won’t open a general discussion, as you say, but it seems to be slowly becoming everyone’s answer to everything. that alone has got to be an anti-pattern?