The Persistence Layer with Spring Data JPA

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.

The Persistence with Spring series:

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.

Reference: The Persistence Layer with Spring Data JPA from our JCG partner Eugen Paraschiv at the baeldung blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply

seven + 6 =

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books