Repositories in Spring Data
We’ll focus on different kinds of Spring Data repository interfaces and their functionality. They are:
Each of these has its own functionality:
- CrudRepository provides CRUD functions
- PagingAndSortingRepository provides methods to do pagination and sort records
- JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch
And so, because of this inheritance relationship, the JpaRepository contains the full API of CrudRepository and PagingAndSortingRepository.
When we don’t need the full functionality provided by JpaRepository and PagingAndSortingRepository, we can simply use the CrudRepository.
Here are the functionalities of CrudRepository:
- save(…) : save an Iterable of entities. Here, we can pass multiple objects to save them in a batch
- findOne(…): get a single entity based on the passed primary key value
- findAll(): get an Iterable of all available entities in database
- count(): return the count of total entities in a table
- delete(…): delete an entity based on the passed object
- exists(…): verify if an entity exists based on the passed primary key value
This interface looks quite generic and simple, but actually, it provides all basic query abstractions needed in an application.
As it extends crudRepositories it contains all same functions as of CrudRepository. Here are the extra functionalities you can get in JpaRepository.
- flush() : flush all pending task to the database
- saveAndFlush(…) : save the entity and flush changes immediately
- deleteInBatch(…) : delete an Iterable of entities. Here, we can pass multiple objects to delete them in a batch
This interface provides a method findAll(Pageable pageable), which is the key to implementing Pagination.
When using Pageable, we create a Pageable object with certain properties and we’ve to specify at least:
- Page size
- Current page number