membersound
membersound

Reputation: 86747

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

Upvotes: 4

Views: 1724

Answers (2)

Meziane
Meziane

Reputation: 1667

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

Upvotes: -3

Alex Shesterov
Alex Shesterov

Reputation: 27525

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

Upvotes: 5

Related Questions