javaspringspring-data-jpaspring-dataspring-repositories

How to use fixed values in Spring CrudRepository?


Is it possible to add fixed values directly in a CrudRepository query method? Like:

findAdults(int age > 17);
findAllByBookingDateAndStatus(
    LocalDate bookingDate = LocalDate.now().minusDays(1),
    TypeStatus status = TypeStatus.FAILED);

Solution

  • As an alternative to custom @Query'es, you may use default methods.

    This is especially useful if default values are calculated in a "complex" way, e.g. LocalDate.now().minusDays(1).

    For example:

    List<Person> findByAgeGreaterThan(int age);
    
    default List<Person> findAdults() {
        return findByAgeGreaterThan(17);
    }
    
    ---
    
    List<Booking> findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
    
    default List<Booking> findAllYesterdaysFailedBookings{
        return findAllByBookingDateAndStatus(LocalDate.now().minusDays(1), TypeStatus.FAILED);
    }