英文:
How to use fixed values in Spring CrudRepository?
问题
可以在CrudRepository
的查询方法中直接添加固定值吗?就像这样:
findAdults(int age > 17);
findAllByBookingDateAndStatus(LocalDate bookingDate = LocalDate.now().minusDays(1), TypeStatus status = TypeStatus.FAILED);
英文:
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);
答案1
得分: 3
作为自定义@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);
}
英文:
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);
}
答案2
得分: -2
第一个问题,只需使用:
findByAgeGreaterThan(Integer age);
第二个问题,只需提供要匹配的值,如下所示:
findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
Spring通过查询名称中使用的词语“LessThan”、“And”、“Between”等来理解您的意图。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论