1. Overview

This article will focus on introducing Spring Data JPA into a Spring 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.

Further reading:

A Guide to JPA with Spring

Setup JPA with Spring - how to set up the EntityManager factory and use the raw JPA APIs.

CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data

Learn about the different flavours of repositories offered by Spring Data.

Simplify the DAO with Spring and Java Generics

Simplify the Data Access Layer by using a single, generified DAO, which will result in elegant data access, no unnecessary clutter.

2. The Spring Data Generated DAO – No More DAO Implementations

As we 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 we need to define and maintain, 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 we need to explicitly define.

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.

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:

  • simply define a new method in the interface
  • provide the actual JPQL 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. This makes 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, as we could potentially express these more concisely through a smaller number of reusable blocks.

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's a very powerful and elegant way of defining new custom access methods with very little effort.

Let's look at an example: if the 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. The query creation mechanism supports a much larger set of keywords.

In case that the parser cannot match the property with the domain object field, we'll see the following exception:

java.lang.IllegalArgumentException: No property nam found for type class com.baeldung.spring.data.persistence.model.Foo

3.2. Manual Custom Queries

Let's now look at a custom query that we'll 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-managed DAO is indeed hidden since we don't work with it directly. However, this is a simple enough implementation – the SimpleJpaRepository – which defines transaction semantics using annotations.

More explicitly, this uses a read-only @Transactional annotation 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.

4.1. Exception Translation Is Alive and Well

The question is now – since Spring Data JPA doesn't depend on the old ORM templates (JpaTemplate, HibernateTemplate) and they have been removed since Spring 5 – are we still going to get our JPA exceptions translated to Spring's DataAccessException hierarchy?

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

Let's verify exception translation 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 JPA Repository Configuration

To activate the Spring JPA repository support we can use the @EnableJpaRepositories annotation and specify the package that contains the DAO interfaces:

@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") 
public class PersistenceConfig { 
    ...
}

We can do the same with an XML configuration:

<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository" />

6. 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 Spring's support for the JPA @PersistenceContext annotation. It uses this 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:

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

7. Maven Dependency

In addition to the Maven configuration for JPA, like in a previous article, we'll add the spring-data-jpa dependency:

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>2.2.7.RELEASE</version>
</dependency>

8. Using Spring Boot

We can also use the Spring Boot Starter Data JPA dependency that will automatically configure the DataSource for us.

We also need to make sure that the database we want to use is present in the classpath. In our example, we've added the H2 in-memory database:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   <version>2.2.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

As a result, just by doing these dependencies, our application is up and running and we can use it for other database operations.

The explicit configuration for a standard Spring application is now included as part of Spring Boot auto-configuration.

We can, of course, modify the auto-configuration by adding our customized explicit configuration.

Spring Boot provides an easy way to do this using properties in the application.properties file:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

In this example, we've changed the connection URL and credentials.

9. Conclusion

This article covered the configuration and implementation of the persistence layer with Spring 5, JPA 2, and Spring Data JPA (part of the Spring Data umbrella project), using both XML and Java-based configuration.

We discussed ways to define more advanced custom queries, as well as transactional semantics, and a configuration with the new jpa namespace. 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.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Matt Trousdale
Matt Trousdale
6 years ago

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
6 years ago
Reply to  Matt Trousdale

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
6 years ago

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
6 years ago
Reply to  Mike Kent

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
6 years ago
Reply to  Oliver Gierke

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
6 years ago
Reply to  Mike Kent

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
5 years ago

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
5 years ago
Reply to  rajan sellapan

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,
Eugen.

Simone Perriello
Simone Perriello
5 years ago

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

Eugen Paraschiv
5 years ago

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,
Eugen.

Simone Perriello
Simone Perriello
5 years ago

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?

Eugen Paraschiv
5 years ago

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,
Eugen.

Simone Perriello
Simone Perriello
5 years ago

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
Terence Taih
4 years ago

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

Eugen Paraschiv
4 years ago
Reply to  Terence Taih

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,
Eugen.

Comments are closed on this article!