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

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

How to use fixed values in Spring CrudRepository?

问题

可以在CrudRepository的查询方法中直接添加固定值吗?就像这样:

  1. findAdults(int age > 17);
  2. 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:

  1. findAdults(int age > 17);
  2. findAllByBookingDateAndStatus(LocalDate bookingDate = LocalDate.now().minusDays(1), TypeStatus status = TypeStatus.FAILED);

答案1

得分: 3

作为自定义@Query的替代,您可以使用默认方法。

这在默认值以“复杂”的方式计算时特别有用,例如LocalDate.now().minusDays(1)

例如:

  1. List<Person> findByAgeGreaterThan(int age);
  2. default List<Person> findAdults() {
  3. return findByAgeGreaterThan(17);
  4. }
  1. List<Booking> findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
  2. default List<Booking> findAllYesterdaysFailedBookings{
  3. return findAllByBookingDateAndStatus(LocalDate.now().minusDays(1), TypeStatus.FAILED);
  4. }
英文:

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:

  1. List&lt;Person&gt; findByAgeGreaterThan(int age);
  2. default List&lt;Person&gt; findAdults() {
  3. return findByAgeGreaterThan(17);
  4. }
  5. ---
  6. List&lt;Booking&gt; findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);
  7. default List&lt;Booking&gt; findAllYesterdaysFailedBookings{
  8. return findAllByBookingDateAndStatus(LocalDate.now().minusDays(1), TypeStatus.FAILED);
  9. }

答案2

得分: -2

第一个问题,只需使用:

  1. findByAgeGreaterThan(Integer age);

第二个问题,只需提供要匹配的值,如下所示:

  1. findAllByBookingDateAndStatus(LocalDate bookingDate, TypeStatus status);

Spring通过查询名称中使用的词语“LessThan”、“And”、“Between”等来理解您的意图。

英文:

For the first one simply use:

  1. findByAgeGreaterThan(Integer age);

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

  1. 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:

确定