Skip to main content

Development

How to Use Spring Data JPA

What Is Spring Data JPA?

Firstly, Spring Data is a subproject of Spring, which used to simplify database access. It supports both NoSQL and relational data storage. Spring Data JPA is not a JPA provider, it just adds an extra layer of abstraction on top of the JPA provider.

At first, it seems like Spring Data JPA makes our code more complex. To some extent, that’s true. It does add an extra layer. But at the same time, it also eliminates the need to write boilerplate code.

If we use Spring Data JPA, we don’t need to worry about the actual implementation of repository abstraction. What we need to do is become familiar with the Spring Data Repository Interface, shown as below:

How to Use Spring Data JPA

Configuration

First, we must configure the environment for our application which uses Spring Data JPA. We need to add necessary libraries (Spring, Spring Data JPA, Spring Data Common, MySQL, c3p0, slf4j…) and configure the application context of our Spring application.

In applicationContext.xml:

1.Configure the Datasource Bean.How to Use Spring Data JPA

2.Configure the Entity Manager Factory Bean.How to Use Spring Data JPA

3.Configure the Transaction Manager Bean.How to Use Spring Data JPA

4.Configure Annotation-Driven Transaction Management.How to Use Spring Data JPA

5.Configure Spring Data JPA.

How to Use Spring Data JPA

6.Configure automatic scanning of packagesHow to Use Spring Data JPA

Creating the Repository

1.Before we create the repository, we must create an entity class. The relevant parts of our entity are shown below:

How to Use Spring Data JPA

2.Now we can create our first repository. We need to create an interface that extends the interface that is provided by Spring Data (e.g. Repository, CrudRepository, PagingAndSortingRepository, QueryDslPredicateExecutor, JpaRepository, JpaSpecificationExecutor…).

  • Repository is an empty interface. It is a tag interface. The interface which inherits the Repository interface will be recognized as a Repository Bean by the IOC container. Then we can use the methods provided by the Repository interface and define some simple methods which meet certain norms in this interface. In fact, we can also use the @RepositoryDefinition annotation instead of inheriting the Repository.
  • If we create the repository by extending the JpaRepository interface, we must provide two parameters: one is the type of the entity that we use in this repository, the other one is the type of the entity’s id field. The source code about the whole repository is as follows:How to Use Spring Data JPA

2.1 Creating Database Queries From Method Names

If we create query methods using the method name, we should follow these rules:

  • The method name must start with a special prefix (e.g. find…By, read…By, get…By, count…By, and query…By).
  • If we want to select unique results, we need to add  Distinct
  • We can use Top or First keywords to limit the number of returned query results.
  • We can specify the search criteria by combining property expressions with supported keywords.
  • We are supposed to use the method name strategy only when the query is simple or only has one or two search conditions.How to Use Spring Data JPA

2.2 Creating Database Queries Using @Query Annotation

  • Using @Query annotation to create a database query precedes all other query generation strategies.
  • @Query annotation supports both JPQL and SQL. You need to set the JPQL or SQL query as the value of the @Query
  • If you use SQL, you should set the value of @Query annotation’s nativeQuery attribute to true.
  • We can add method parameters to the query method and configure the name of the named parameter by annotating the method parameter with @Param

The relevant code is as follows:

How to Use Spring Data JPA

  • We can also use custom JPQL to use UPDATE and DELETE But it must be modified with @Modifying annotation which is used to inform Spring Data that it is an UPDATE or DELETE operation. It also needs to use the transaction in the service layer.

The relevant code is as follows:

How to Use Spring Data JPAHow to Use Spring Data JPA

2.3 Simple Sorting and Pagination Using PagingAndSortingRepository

If the repository we created extending the  PagingAndSortingRepository interface or the subinterface of it, we can use the findAll (Pageable var1) method which is very simple to implement paging queries.

The relevant code is as follows:

How to Use Spring Data JPAHow to Use Spring Data JPA

2.4 Creating Database Queries With the JPA Criteria API

  • Our repository interface must extend the JpaSpecificationExecutor<T> interface so we can specify the conditions of our database queries by creating new Specification<T> objects.

Relevant code about Pagination (condition: data whose id>5) is as follows:How to Use Spring Data JPA

2.5 Adding Custom Methods Into a Single Repository

Now we can use plenty of CRUD operations provided by Spring Data JPA and creating database queries using method names and @Query Annotation.

If that’s still not enough, for example, sometimes we need to do things that are not supported by Spring Data JPA. In this case, we can extend our own repository by adding custom methods into it following these steps:

2.5.1 Create a custom repository interface:

  1. Create an interface: CustomPersonRepository
  2. Add custom method to the created interface.How to Use Spring Data JPA

2.5.2 Implementing the custom repository interface:

  • Create a class which implements the CustomPersonRepository The name of this class must follow the syntax: [The name of the repository]Impl.
  • How to Use Spring Data JPA

2.5.3 Adding the custom method into repository:

  • Modify the repository to extend the CustomPersonRepository.How to Use Spring Data JPA

2.5.4 Then we can use our own custom method:

How to Use Spring Data JPA

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories
Follow Us