Spring Data JPA - Reasons to use

OK, so if the JPA specification and its implementations provide most of the features that you use with Spring Data JPA, do you really need the additional layer? Can’t you just use the Hibernate or EclipseLink directly?

You can, of course, do that. That’s what a lot of Java SE applications do. Jakarta EE provides a good integration for JPA without adding an extra layer.

But the Spring Data team took the extra step to make your job a little bit easier. The additional layer on top of JPA enables them to integrate JPA into the Spring stack seamlessly. They also provide a lot of functionality that you otherwise would need to implement yourself.

Here are some features that Spring Data adds on top of JPA.

1. No-code Repositories

The repository pattern is one of the most popular persistence-related patterns. It hides the data store specific implementation details and enables you to implement your business code on a higher abstraction level.

Implementing that pattern isn’t too complicated but writing the standard CRUD operations for each entity creates a lot of repetitive code. Spring Data JPA provides you a set of repository interfaces which you only need to extend to define a specific repository for one of your entities.

Here is a quick example of a repository that provides the required methods:

  1. to persist, update and remove one or multiple Author entities,
  2. to find one or more Authors by their primary keys,
  3. to count, get and remove all Authors and
  4. to check if an Author with a given primary key exists.
package org.thoughts.on.java.spring.data.repository;

import org.springframework.data.repository.CrudRepository;
import org.thoughts.on.java.spring.data.model.Author;

public interface AuthorRepository extends CrudRepository<Author, Long> {}

That code sample is correct and complete. The CrudRepository interface defines all methods that we talked about before. So, you just need to extend it.

2. Reduced boilerplate code

To make it even easier, Spring Data JPA provides a default implementation for each method defined by one of its repository interfaces. That means that you no longer need to implement basic read or write operations. And even so all of these operations don’t require a lot of code, not having to implement them makes life a little bit easier and it reduces the risk of stupid bugs.

3. Generated queries

  1. Spring Data JPA - Generated Queries

References

https://thorben-janssen.com/what-is-spring-data-jpa-and-why-should-you-use-it/#reasons


Links to this note