如何在Spring的CrudRepository中使用固定值?

huangapple go评论59阅读模式
英文:

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&lt;Person&gt; findByAgeGreaterThan(int age);

default List&lt;Person&gt; findAdults() {
    return findByAgeGreaterThan(17);
}

---

List&lt;Booking&gt; findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);

default List&lt;Booking&gt; 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

huangapple
  • 本文由 发表于 2020年10月1日 17:23:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64152448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定