如何将多个日期之间的搜索与Spring Data JPA的CrudRepository结合? [英] How to combine multiple date-between searches with CrudRepository of Spring Data JPA?

查看:122
本文介绍了如何将多个日期之间的搜索与Spring Data JPA的CrudRepository结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以下工作正常:

@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?

推荐答案

Between 关键字自然会绑定两个参数。因此,在绑定了from子句之后,参数列表将被耗尽,并且我们不知道将哪些参数用于第二个条件。

The Between keyword 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.

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

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);
}

这篇关于如何将多个日期之间的搜索与Spring Data JPA的CrudRepository结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆