I just announced the new Spring Boot 2 material, coming in REST With Spring:


Table of Contents

1. Overview

This article will focus on introducing Spring Data JPA into a Spring 4 project and fully configuring the persistence layer. 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. The Spring Data generated DAO – 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: a decrease in the number of artifacts that need to be defined and maintained, 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 needs to be explicitly defined.

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

By extending the interface we get the most relevant CRUD methods for standard data access available in a standard DAO out of the box.

3. 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:

  • simply define a new method in the interface
  • provide the actual JPQ query by using the @Query annotation
  • use the more advanced Specification and Querydsl support in Spring Data
  • define custom queries via JPA Named Queries

The third option – the Specifications and Querydsl support – is similar to JPA Criteria but using a more flexible and convenient API – making the whole operation much 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.

This last option has the disadvantage that it either involves XML or burdening the domain class with the queries.

3.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 names. While this has some limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort.

Let’s look at an example: if the managed entity has a name field (and the Java Bean standard getName and setName methods), we’ll define the findByName method in the DAO interface; this will automatically generate the correct query:

public interface IFooDAO extends JpaRepository< Foo, Long >{

   Foo findByName( 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 org.rest.model.Foo

3.2. Manual Custom Queries

Let’s now look at a custom query that we will define via the @Query annotation:

@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);

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.

4. Transaction Configuration

The actual implementation of the Spring Data managed DAO is indeed hidden since we don’t work with it directly. However – it is a simple enough implementation – the SimpleJpaRepository – which defines transaction semantics using annotations.

More explicitly – a read-only @Transactional annotation is used at the class level, which is then overridden for the nonread-only methods. The rest of the transaction semantics are default, but these can be easily overridden manually per method.

4.1. Exception Translation is Alive and Well

The question is now – since we’re not using the default Spring ORM templates (JpaTemplate, HibernateTemplate) – are we losing exception translation by using Spring Data JPA?-Are we not going to get our JPA exceptions translated to Spring’s DataAccessException hierarchy?

Of course not – exception translation is still enabled by the use of the @Repository annotation on the DAO. This annotation enables a Spring bean postprocessor to advice all @Repository beans with all the PersistenceExceptionTranslator instances found in the Container – and provide exception translation just as before.

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

@Test(expected = DataIntegrityViolationException.class)
public void givenFooHasNoName_whenInvalidEntityIsCreated_thenDataException() {
    service.create(new Foo());

Keep in mind that 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.

5. Spring Data Configuration

To activate the Spring JPA repository support with an XML configuration – we’ll use the jpa namespace and specify the package where to DAO interfaces are located:

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

<jpa:repositories base-package="org.rest.dao.spring" />


Starting with Spring Data 1.4, we can do the same with Java-only configuration:

@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceConfig { ... }

6. The Spring Java or XML Configuration

We already discussed in great detail how to configure JPA in Spring in a previous article. 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 for creating the actual DAO implementations – JpaRepositoryFactoryBean.

In addition to the already discussed configuration, we also need to include the Spring Data XML Config – if we are using XML:

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

7. The Maven Dependency

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


8. Conclusion

This article covered the configuration and implementation of the persistence layer with Spring 4, JPA 2 and Spring Data 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 a 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.

The implementation of this Spring Data JPA Tutorial can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

I just announced the new Spring Boot 2 material, coming in REST With Spring:


newest oldest most voted
Notify of

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… Read more »

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… Read more »

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
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?

Oliver Gierke

Any chance you back your claims with some arguments? Can you give examples of the shortcomings you’ve identified? Which “it” are you referring to exactly? Happy to hear about those as we might be able to address them.

Spring Data JPA aims to ease the implementation of JPA based persistence layers with Spring. That’s pretty focused I think. If “it” is the Spring stack in general: do you consider a toolbox a bad, and bloated thin, just because has screwdrivers *and* hammers *and* nails? Right tool for the job, I’d argue…

Mike Kent
Mike Kent

I think getting rid of the Dao is a mistake. There isn’t enough abstraction on the Spring Data JPA repository to warrant calling it a Dao.

Oliver Gierke

Care to elaborate? What is it that you’re missing being abstracted? Nobody’s getting rid of the DAO. We embrace the pattern and offer an easy (non-)implementation model. That’s it :).

Mike Kent
Mike Kent

Certainly. Let’s say we throw a simple guava cache(in lieu of spring cache) on top of the repository. A consumer of the IFooDao shouldn’t care where the data comes from (cache, DB, service, etc) and the Dao would handle that abstraction.

Oliver Gierke

That’s exactly what the Spring Data repository abstraction provides. Maybe some of the post’s headlines are misleading in that regard. Spring Data takes the effort out of the *boilerplate* repository code. You’re still free to implement the parts you *want* to code manually yourself (see this section of the reference docs [0] for example). We of course also integrate with the Spring caching abstraction. So you still have full control over what you want implement, you just can rely on the boring parts being taken care of for you.

[0] http://docs.spring.io/spring-data/jpa/docs/current/reference/html/repositories.html#repositories.single-repository-behaviour

rajan sellapan
rajan sellapan

hello sir, I could not run maven project, can you give download link for eclipse war , OR can you give one article how to run your tutorial project, so I can understand and run the examples, please help sir,

Eugen Paraschiv

Hey Rajan – I double checked and the project builds fine. It’s a maven project, so you’ll have to simply run a “mvn clean install” to fully build it and produce the war file. Cheers,