How Spring Data JPA works?

Spring Data JPA is a lib that's turned easier the data access in Java applications using Spring Framework. It's allow that developers write queries using a specified domain language, based upon method names or annotations. Beyond that, it's offered support to a couple of features such as pagination, ordination, cache, audit and projections. In this article I'll explain how Spring Data JPA works internally and which are their advantages and disadvantages.

Spring Data JPA x JPA x Hibernate

Before we continue, let's first understand a bit about these guys:

  • JPA

JPA or Java Persistence API is a spec that defines an API to object-relational mapping that simplifies the implementation of data access layer in a Java application.

  • Hibernate

Hibernate is one of the most popular implementations of JPA specification.

  • Spring Data JPA

Well, we already know what is the Spring Data JPA, but which is his purpose? The Spring Data JPA adds a new layer to Java Persistence API, i.e., allows you to use all power of JPA in your application and at top of it adds it's own features such as the no-code repository pattern implementation, results pagination and semi-automatic ordering, automatic generations of SLQ queries and reduces the writing of repetitive code.

Repository pattern no-code implementation

The repository pattern is onde of the mos used patterns related to data persistence. It's abstract the data access logical, providing a common interface to data manipulation, which allows isolate the application domain from the implementation details of data persistence layer, turning easier the code maintenance and testing.

The implementation of this pattern is not too complex, however, in an application where there are many entities to be mapped, writing the default operations of a CRUD for each one of these entities could produce a repetitive code as a result.

Bellow, we got a repository example that provides all the necessary methods to:

  • update, persists and remove one person or multiple people;
  • find one person or more people by their PK;
  • list, count or remove all people;
  • check if a person with a specified PK exists
package com.ronilsonalves.springjpa.data;

import com.ronilsonalves.springjpa.model.Person;
import org.springframework.data.repository.CrudRepository;

public interface PersonRepository extends CrudRepository<Person, Long> {
  // That's all we need!
}

In a service class we can inject this repository as dependency and access the default methods of a CRUD provided by the Spring Data JPA without even wrote their signatures in our repository:

package com.ronilsonalves.springjpa.service;

import com.ronilsonalves.jparestapi.data.PersonRepository;
import com.ronilsonalves.jparestapi.model.Person;

public class PersonServiceImpl implements PersonService {
    private final PersonRepository personRepository;

    /**
     * The @Autowired annotation is optional and is used to inject the PersonRepository dependency.
     * @param personRepository our Person repository interface
     */
    public PersonServiceImpl(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    /**
     * This method saves a Person object in the database. Observe that in our Person repository we don't have a
     * method signature or a custom query to save a person.
     * @param person the Person object (or could be a DTO) to be saved
     * @return the Person object
     */
    public Person savePerson(Person person) {
        return personRepository.save(person);
    }

    /**
     * This method returns a Person object by its id. Again, observe that in our Person repository we don't have a
     * method signature or a custom query to find a person by its id.
     * @param personId the id of the person to be returned
     * @return the Person object
     * @throws RuntimeException if the person is not found
     */
    public Person getPerson(Long personId) throws RuntimeException {
        return personRepository.findById(personId).orElseThrow(
                () -> new RuntimeException("Person not found")
        );
    }
    
    /* Omited for brevity  */
}

Pagination and ordination

The Spring Data JPA provides an interface that allows the implementation of resources of pagination, ordination and sorting in a simplified way, in addition, you can use it with the CrudRepository, as seen above in our PersonRepository that extends of Spring Data JPA CrudRepository interface. Let's go apply a pagination and ordination to our results:

package com.ronilsonalves.springjpa.data;

import com.ronilsonalves.jparestapi.model.Person;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

@Repository
public interface PersonRepository extends CrudRepository<Person, Long>, PagingAndSortingRepository<Person, Long> {
  
    // We don't need to declare the signature of method to find all people and apply pagination, Spring Data JPA do it for us and order the results (by PK as default).

    
    // Query generation and ordination

    /**
     * This method returns a Page object containing Person objects qyerying by last name, ordered by first name and 
     * applying it pagination.
     * @param name the last name of the people to be returned
     * @param pageable the Pageable object
     * @return a Page object containing Person objects
     */
    Page<Person> findAllByLastNameOrderByFirstName(String name, Pageable pageable);
}

To exemplify the pagination and ordination, our PersonRepository is extending now also from PagingAndSortingRespository (other useful interface of the Spring Data JPA), beyond the imports, was necessary write ONLY ONE line of code.

In our service class, we can call the method findAll() — again, without written it's method signature in our repository — passing as parameter a Pageable object.

To ordination, we need to call the method that generates the JPQL query (soon I'll talk about this feature of the Spring Data JPA) and as result return a page of persons (people):

package com.ronilsonalves.springjpa.data;

import com.ronilsonalves.jparestapi.data.PersonRepository;
import com.ronilsonalves.jparestapi.model.Person;

public class PersonServiceImpl implements PersonService {

    /* Omited for brevity  */

    /**
     * This method returns a Page object containing Person objects. Observe that in our Person repository we don't have
     * a method signature or a custom query to find all people applying it pagination.
     * @param page the page number
     * @param size the page size
     * @return a Page object containing Person objects
     */
    public Page<Person> personPageable(int page, int size) {
        return personRepository.findAll(PageRequest.of(page, size));
    }

    /**
     * This method returns a Page object containing Person objects.
     * @param lastName the last name of the people to be returned
     * @param page the page number
     * @param size the page size
     * @return a Page object containing Person objects
     */
    public Page<Person> personPageableByLastName(String lastName, int page, int size) {
        return personRepository.findAllByLastNameOrderByFirstName(lastName, PageRequest.of(page, size));
    }

    /* Omited for brevity  */
}

Queries generation

The Spring Data JPA allows the generation of queries to database based upon name of the methods defined in the repository. For queries not too much complexes, you can use this magical tool defining a method in repository starting by find...by, the Spring so "translate" the name of the method and creates a JPQL query for it. We've seen examples of this implementation in our repository in the code examples above:

package com.ronilsonalves.springjpa.data;

/* Omited for brevity  */

@Repository
public interface PersonRepository extends CrudRepository<Person, Long>, PagingAndSortingRepository<Person, Long> {

    /* Omited for brevity  */
  
    Page<Person> findAllByLastNameOrderByFirstName(String name, Pageable pageable);
}

But the magic of this resource doesn't stop there, with it, also you can create manual customized queries using JPQL query and @Query annotation.

Custom queries

The custom queries are a great tool and you can use it for more complex queries or in custom queries, to do it you need just annotate the method signature in the repository with @Query annotation provided by Spring Data JPA. For example, supposing that Person entity has the following attributes: name, lastname, date_of_birth and email address. If you want to find all people who have between 18 and 25 years old and that their email addresses are ending in "@gmail.com", so you can use a native SQL query to build our custom query as you can see below:

package com.ronilsonalves.springjpa.data;
    
// Omited for brevety

public interface PersonRepository extends PagingAndSortingRepository<Person, Long>, CrudRepository<Person, Long> {
    // Omited for brevety
  
    // Custom query generation

    /**
     * This method returns a List object containing Person objects querying their age range and ending mail using
     * a native query.
     * @param minAge the minimum age
     * @param maxAge the maximum age
     * @param endingMail the ending mail
     * @return a List object containing Person objects
     */
    @Query(value = "SELECT * FROM person " +
            "WHERE TIMESTAMPDIFF(YEAR, date_of_birth, CURRENT_DATE) BETWEEN :minAge AND :maxAge " +
            "AND LOWER(email) LIKE LOWER(CONCAT('%', :endingMail))", nativeQuery = true)
    List<Person> retrievePersonsByAgeAndEMailNative(@Param("minAge") int minAge, @Param("maxAge") int maxAge,
                                   @Param("endingMail") String endingMail);

}

With the custom queries in addition, you can use JPQL queries also you can use native queries as seen in the previous code.

Reduces the writing of repetitive code

As you have seen in the previous examples, was not necessary write methods to create, read, update and delete data from database related to the Person entity, making easier the data manipulation in data persistence layer and how I've exemplified previously, in a system with many entities to be mapped, it wouldn't be necessary write several times the same methods to save/update, read and delete data from an object, all this thanks to the no-code implementation of repository pattern.

Disadvantages

As not everything are flowers, until here you have seen many vantages of Spring Data JPA being used in you Java application, but the use must consider the possible negative effects:

  • Strong coupling between the entities and the API

The Spring Data JPA can leas to a strong coupling between the entities and the API making difficult the code maintenance if not used a good approach of separation of responsibilities.

  • Performance issues

The Spring Data JPA can present performance difficulties when working with more complex queries or a large flow of data.

  • Limitations on query customization

Despite enabling the creation of automatic queries using the name of methods — and gives freedom to create custom queries using the JPQL, this customization may suffer imitations, which may turn it into a problem on the creation of complex queries using the Spring Data JPA.

Conclusion

You have seen the main characteristics of the Spring Data JPA and several examples of its application in the application development, You could observe the It's practicality making easier the management of data persistence layer and some disadvantages that mus be considered in Spring Data JPA adoption.

See also