How to use fixed values in Spring CrudRepository?

1.3k Views Asked by At

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);
2

There are 2 best solutions below

4
On BEST ANSWER

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);
}
1
On

For the first one simply use:

findByAgeGreaterThan(Integer age);

For the second one, just provide the values to match like so:

findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);

Spring undestand what you want using the used words "LessThan", "And", "Between" and the like in the name of the queries