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

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 an Eclipse based project, so it should be easy to import and run as it is.

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

  • Guest

    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.

    • 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.

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

    • 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

    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.

    • 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

        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.

        • 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

    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,

    • 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,

  • Simone Perriello

    So, in Spring Data, there is no difference at all between a DAO or a Repository?

    • Well, there’s a whole lot of literature around this – and yes, there are differences, but Spring doesn’t use the @Repository concept in the exact way it’s mapped out in DDD, so for the purposes of Spring Data and this article, yes – you can use them interchangeably. Cheers,

      • Simone Perriello

        Hey Eugen, thanks for your quick reply.
        Well, I’m asking this because I’m working on a legacy project in which every domain entity has:
        – a generic interface EntityDao with basic CRUD operations
        – a class EntityDaoSomeIplmenetation (in this case it is a Neo4j Implementation), that implements EntityDao; these implementations are marked as a @Service and contains a field @Autowired EntityRepository
        – a class EntityRepository, which extends some Repository (in this case, a GraphRepository).
        In general, what do you think of this approach?

        • The naming convention is a bit confusing and not really inline with the standard meaning of these artifacts. I would simplify things by simply renaming the DAOs to Service (since they’re using the @Service annotation). That will make things a lot more standard – you would basically have a Service layer using a Repository layer – which is perfectly fine. Hope it helps. Cheers,

          • Simone Perriello

            Yes, from the examples I’ve seen around here I guessed that this is more a naming convention. Thanks for your help and for your great work btw 🙂

  • Terence Taih

    Hi friend,
    Thank for you good article and sorry because I ask very late.
    Would you please advice me incase I want to use JPARepos with Session concept? I mean the Session concept in Hibernate, where we can work with persistent object (yes it’s related to attach – detached object).
    I have situation that ONETOMANY relationship. Parent A has many children B. So in first stage, we show this data to web UI, user can add or delete B from A, after that, they click save. All of this action is Cascade. So the result should be the deleted B, the added B or the update B will all save to database. Can we solve this issue with JPA?

    • Hey Terence,
      You can very likely work within JPA only, but if you do need to do any Hibernate specific work, you can always have a look at my Hibernate 4 intro. Now – since this is a more involved scenario, my suggestion is to post the full details (a working example, not just a rough description) to StackOverflow, and then email me the link – I’d be happy to have a look. Hope it helps. Cheers,

  • Deepak Pandey

    Hi . Thanks for nice article.
    Please explain the concept how spring creates implementation class for DAO by using
    @Repository on interface extending jparepository interface. Other Annoataion on interface are also allowed in Spring 4

    • Hey Deepak – glad you like the article.
      @Repository behaves just as @Component (in fact, that’s what it is) – so it instantiates these DAO beans just as any other component. Now, the interface – that comes out of Spring Data, so it’s not core Spring. But, generally speaking – there’s not a whole lot special about these beans – they get created during the bootstrapping of the context, just as any other bean.
      Hope that helps. Cheers,

      • Deepak Pandey

        Thanks for reply Eugen. I understand the point you have mentioned, you are right @repository creates beans of a class as @component or @service do. But in Spring 4 we can use @Repository on an interface which extends JpaRepository. Please refer the following link http://hantsy.blogspot.in/2013/10/spring-data-jpa.html. In this case how @Repository on interface can create bean for an interface. As interface are pure abstarct than how they can be instatiated by using @Repository. Please share your thoughts. Thanks

        • That’s interesting, but I don’t think that annotation does anything (although I haven’t dug into this lately). Basically the way these repos are instantiated is by pointing Spring Data JPA to the right package. For example, you can do that with the following annotation: @EnableJpaRepositories(basePackages = “…”)
          That’s the way these are actually instantiated into beans.
          Hope that helps. Cheers,

          • Deepak Pandey

            Thanks for reply. Eugen @EnableJpaRepositories is used to scan the packages as per my knowlege. Also refer this link https://dzone.com/articles/persistence-layer-spring-data, it states that if we use @Respository on DAO interface and extends Jparespository then we don’t need any implementation forDAOinterface. Spring will create implementation itself. But how not got the reply. Please share if you will get answer. Thanks

          • Hey Deepak – first off, that’s an old article of mine 🙂
            Second – no, I don’t think I state that in the article. Yes, you don’t need any implementation, the interface is enough. But you do need the @EnableJpaRepositories (or the XML equivalent – jpa:repositories base-package).
            You can’t just annotate the interface with @Repository.
            Hope that makes sense. Cheers,

  • Ben Steinhauer

    @EugenParaschiv : I struggle with the separation of concern principle and object-relational impedance mismatch when it comes to distinguishing persistence models (data access layer) from domain models (business layer) and how it is being played out in Spring Data.

    According to my knowledge it is good practice to not use persistence models as domain models. A simple example would be: Due to the bean nature of a persistence model (getters and setters) one does not want to expose setters inside the domain model. Hence, one needs 2 models: 1 for the business layer and 1 for the data access layer.
    See: http://www.mehdi-khalili.com/orm-anti-patterns-part-4-persistence-domain-model/

    Looking at the way Spring Data uses Repository interfaces I can’t seem to figure out how Spring maps from a domain model to a persistence model and vice-versa, unless one writes a DAO that handles the mapping.
    Can you please shed some light into this problem…

    • Hey Ben,
      That’s certainly an interesting question, and one with a broad scope.
      Now, hand-waving all of that away, let me focus on your question and give you a simple answer: Spring doesn’t.
      So – you have your Spring Data repos and your persistence level entities. After that point the way you use them is entirely up to you. You can (and mostly should) have a separate domain layer, or you can ignore that. The point is – Spring isn’t opinionated about that and doesn’t push you one way or another.
      Hope that clears things up. Cheers,