The Repository component in Spring Boot

In this post we will understand what a Repository Component is and how to create a CrudRepository in Spring Boot.

What is a Repository component

A @Repository is a Spring component and stereotype that is part of the ‘persistence layer’. The persistence layer is the way our microservice stores and retrieves the entities it needs.

Persistence Layer

An entity is the class of our application that represents an object of your business, for example a User, Customer, Product, etc.
If our application needs a User (user with his first name, last name, date of birth) and needs to store it, this User is an entity of our domain model and is part of the persistence layer.

A microservice is divided into layers, being the repository the persistence layer that has access to the data and can manipulate it.
Read this other article where we have worked with the Components and Stereotypes in Spring Boot

Spring Boot Controller

How do we create the Repository component?

In Spring a ‘Repository’ is the component in charge of resolving the access to the data of our microservice. If we need to save, modify, delete records of a ‘User’ of the system; then the UserRepository component will be in charge of making direct changes on the User records.

Spring provides us with the basic functionality to store, delete and search entities. For this we have all the interfaces that extend “org.springframework.data.repository.Repository” .

Spring Boot Repository Hierarchy

For our User entity we can think of the basic operations to create, modify and search (CRUD).
CRUD is an acronym that refers to the four minimum functions on an entity –> Create, Read, Update, Delete.

Our entity looks like this:

@Entity
public class User {

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String surname;
    private LocalDate birthDate;
    
    // sets, gets... 
    

CrudRepository

Let’s create an interface UserRepository that will extend CrudRepository.
We annotate the class ‘UserRepository’ as a @Repository component.

CrudRepository is a generic interface that receives two types. The first is the class that this interface will handle, and the second is the data type of the entity’s ID.

The methods provided by CrudRepository are:

  • save: saves an entity
  • saveAll: saves the entities of an iterable list
  • findById: searches for the identifier
  • existsById: checks if an identifier exists
  • findAll: returns all elements for the entity
  • findAllById: searches for all elements having the identifier
  • count: returns the total number of records for the entity
  • deleteById: deletes a record for the identifier
  • delete: deletes the entity
  • deleteAllById: deletes all the elements corresponding to the id
  • deleteAll(Iterable): deletes all the elements received in the parameter
  • deleteAll(): deletes all elements

Spring Boot Crud Repository

Notice, that we do NOT implement the interface. We create a new interface and extend CrudRepository.
Spring will be in charge of the implementation of the interface with the concrete class.

Our UserRepository interface that extends CrudRepository.

import com.example.springbootcourse.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}

With this we have already created our repository with the CRUD operations for our entity.
We can use them from our service

JPARepository

JPARepository inherits all CrudRepository methods. Therefore, we can use all the methods of the CrudRepository interface. Also, JPARepository inherits from PagingAndSortingRepository, with methods for find with sort and paging.

JPARepository also adds other methods. JPARepository api.

  • saveAndFlush: saves an entity and flushes changes instantly.
  • flush: flushes all pending changes to the database.
  • saveAllAndFlush: saves all entities and flushes changes instantly.
  • deleteAllInBatch: deletes the given entities in a batch
  • deleteAllByIdInBatch: deletes the entities identifier
  • deleteAllInBatch: deletes all entities in a batch
  • getById: returns a reference to the entity with the given identifier
  • findAll(Sort): returns all entities sorted
  • findAll(Pageable): returns a Page of entities

Spring Boot JPA Repository

Custom method queries

In all @Repository, we can create a “custom query methods”. Spring automatically generates sql queries using the method name.

For example, this method will automatically generate this query:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

  List<User> findUserByNameAndBirthDate(String name, LocalDate birthDate);

  // result -> select u from User u where u.name = ? and u.birthdate = ?;

}

Observe, we created the methods using the names of the attributes of our ‘User’ entity. In this case, we want to use “and” en our query.

Query Method Name

It is possible to create queries with the most common SQL statements. Please, check

Query Method Spring Query Methods

Conclusion

In this article we learned what is Repository in SpringBoot, and we created a CRUD using the Repository interface.

If you wish to send me any corrections or suggestions, please contact me.
Thanks for your feedback :)

See also