Spring Data JPA provides a familiar and consistent, Spring-based programming model for data access
while still retaining the special traits of the underlying data store.
It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based
data services.
Introduction
This is the fifth part part of a series of posts focused on Hibernate and JPA. In my previous post we saw how to abstract away
most of the logic written in prior post with Spring. In this post we will
look at abstracting away the CRUD layer to Spring Data JPA and writing less boilerplate code.
We will end this post by externalizing our database configuration to a .properties file.
To enable the project to use Spring Data we need the following dependencies
spring-data-jpa
Modify the pom.xml file by adding the following dependencies:
Refactoring the PersonRepository Interface
We would extend the Spring Data Repository marker interface. The general purpose here is to hold type information as well as being
able to discover interfaces that extend this one during classpath scanning for easy Spring bean creation.
We specify the generic type arguments as the Person entity and id type (Long).
Next we will add a Spring Data repository scanning mechanism (@EnableJpaRepositories) to our configuration class to detect this
interface.
Spring Data uses several query lookup strategies to create queries based on method names.
You can read more on the reference documentation.
To support this so as not to write too much code we will refactor the PersonRepository.
Spring Data Repositories are transactional by default that’s why the above snippet is missing the @Transactional annotation.
Externalizing Configuration
Up until now we have been hardcoding configuration values into our source code. In a big project you would often find yourself
writing configuration values in external files and programmatically calling those values in your source code.
Create a file application.properties.
file: src/main/resources/application.properties:
The application.properties file will be loaded into our application using Spring’s Resource
lookup mechanism.
In this post we added Spring Data JPA to reduce CRUD boilerplate code. We also extracted configuration values into an external file.
As usual you can find the full example to this guide in the github repository. Until the next post, keep doing cool things .