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

查看:18
本文介绍了如何将多个日期之间的搜索与 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天全站免登陆