Alphalearningschool
        

<<< Prev

Next >>>

Up
Repositories in Spring Data

We’ll focus on different kinds of Spring Data repository interfaces and their functionality. They are:

  1. JpaRepository
  2. CrudRepository
  3. PagingAndSortingRepository

Let’s start with the JpaRepository – which extends PagingAndSortingRepository and, in turn, the CrudRepository.

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.

 CrudRepository:

Here are the functionalities of CrudRepository:

  1. save(…) : save an Iterable of entities. Here, we can pass multiple objects to save them in a batch
  2. findOne(…): get a single entity based on the passed primary key value
  3. findAll(): get an Iterable of all available entities in database
  4. count(): return the count of total entities in a table
  5. delete(…): delete an entity based on the passed object
  6. 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.

JpaRepository:

As it extends crudRepositories it contains all same functions as of CrudRepository. Here are the extra functionalities you can get in JpaRepository.

  1. flush() : flush all pending task to the database
  2. saveAndFlush(…) : save the entity and flush changes immediately
  3. deleteInBatch(…) : delete an Iterable of entities. Here, we can pass multiple objects to delete them in a batch

PagingAndSortingRepository:

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:

  1. Page size
  2. Current page number
  3. Sorting