Spring data repositories provide a powerful way to interact with databases.

Repository Interface

Spring data has multiple repository interfaces:

  • Repository<T, ID>: Marker interface for repositories.
  • CrudRepository<T, ID>: Provides CRUD operations.
  • PagingAndSortingRepository<T, ID>: Extends CrudRepository with paging and sorting.
  • JpaRepository<T, ID>: Extends PagingAndSortingRepository with JPA-specific operations.
classDiagram
  direction RL

  class Repository~T, ID~
  <<interface>> Repository
  class CrudRepository~T, ID~
  <<interface>> CrudRepository
  class PagingAndSortingRepository~T, ID~
  <<interface>> PagingAndSortingRepository
  class JpaRepository~T, ID~
  <<interface>> JpaRepository

  JpaRepository <|-- PagingAndSortingRepository
  PagingAndSortingRepository <|-- CrudRepository
  CrudRepository <|-- Repository

The JPA repositories automatically generate queries based on method names. Therefor, is reduces the code which needs to be written.

Query Methods

Query methods are methods that are automatically implemented by Spring data. They are based on the method name and return type.

The documentation provides the full list of supported keywords: Spring Data JPA - Query Methods

An overview of the most common keywords:

  • And, Or: Combine multiple conditions.
  • Is, Equals: Equality query.
  • Between: Range query, requires two parameters.
  • LessThan, GreaterThan, LessThanEqual, GreaterThanEqual: Comparison query.
  • Containing, Like, StartingWith, EndingWith: String matching, placing wildcards depending on selected condition.
  • IgnoreCase: Ignore case when comparing.
  • True, False, Null, NotNull: Get all records where the column value matches the condition.
  • Not: Negate the condition of the query.
  • In, NotIn: Check if collection contains/does not contain element.

Example

  public interface RentalRepository extends JpaRepository<Rental, Long> {
    List<Rental> findByUser(User user);
    List<Rental> findByMovieTitleContains(String title);
    List<Rental> findByMoviePriceCategoryIs(PriceCategory pc);
}
  

Custom Queries

Custom queries can be written using the @Query annotation.

Example

  public interface RentalRepository extends JpaRepository<Rental, Long> {
    @Query("SELECT r FROM Rental r WHERE r.user = :user")
    List<Rental> findByUser(User user);
}
  

Specifications

Specifications are a way to define complex queries in a type-safe way. They are an extension of the Criteria API.

Example

  public interface RentalRepository extends JpaRepository<Rental, Long>, JpaSpecificationExecutor<Rental> {
    default List<Rental> findByUser(User user) {
        return findAll((root, query, cb) -> cb.equal(root.get("user"), user));
    }
}