Java 如何将多个日期之间的搜索与 Spring Data JPA 的 CrudRepository 结合起来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25870095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:22:23  来源:igfitidea点击:

How to combine multiple date-between searches with CrudRepository of Spring Data JPA?

javaspringpostgresqlspring-data-jpa

提问by membersound

spring-data provides a way to generate SQL search by defining the method name.

spring-data 提供了一种通过定义方法名来生成 SQL 搜索的方法。

The following works fine:

以下工作正常:

@Entity
public class Book {
  Date from, to;
}

//CrudRepository<Book>
findByFromDateBetween(Date departure, Date arrival);

But why then does the following not work?

但是为什么下面的方法不起作用?

findByFromDateBetweenAndToDateBetween(Date departure, Date arrival);

To connect two date searches, I have to repeat the date:

要连接两个日期搜索,我必须重复日期:

findByFromDateBetweenAndToDateBetween(Date departure, Date arrival, Date departure, Date arrival);

Question: is it possible to reuse the params?

问题:是否可以重用参数?

采纳答案by Oliver Drotbohm

The Betweenkeyword naturally binds two parameters. Thus after binding the from clause, the parameter list is exhausted and we don't know which parameters to use for the second criteria.

Between关键字自然结合两个参数。因此,在绑定 from 子句后,参数列表已用尽,我们不知道第二个条件使用哪些参数。

A manually defined query should do the trick:

手动定义的查询应该可以解决问题:

interface BookRepository extends Repository<Book, Integer> {

  @Query("select b from Book b " +
         "where b.from between ?1 and ?2 and b.to between ?1 and ?2")
  List<Book> findByDatesBetween(Date departure, Date arrival);
}