如何在 Spring CrudRepository 中使用固定值?
How to use fixed values in Spring CrudRepository?
是否可以在CrudRepository
查询方法中直接添加固定值?喜欢:
findAdults(int age > 17);
findAllByBookingDateAndStatus(LocalDate bookingDate = LocalDate.now().minusDays(1), TypeStatus status = TypeStatus.FAILED);
对于第一个,只需使用:
findByAgeGreaterThan(Integer age);
对于第二个,只需提供要匹配的值,如下所示:
findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
Spring 在查询名称中使用“LessThan”、“And”、“Between”等词来理解您想要的内容
作为自定义 @Query
的替代方法,您可以使用默认方法。
如果以“复杂”方式计算默认值,这尤其有用,例如LocalDate.now().minusDays(1)
.
例如:
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);
}
是否可以在CrudRepository
查询方法中直接添加固定值?喜欢:
findAdults(int age > 17);
findAllByBookingDateAndStatus(LocalDate bookingDate = LocalDate.now().minusDays(1), TypeStatus status = TypeStatus.FAILED);
对于第一个,只需使用:
findByAgeGreaterThan(Integer age);
对于第二个,只需提供要匹配的值,如下所示:
findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
Spring 在查询名称中使用“LessThan”、“And”、“Between”等词来理解您想要的内容
作为自定义 @Query
的替代方法,您可以使用默认方法。
如果以“复杂”方式计算默认值,这尤其有用,例如LocalDate.now().minusDays(1)
.
例如:
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);
}