【问题标题】:Spring Data MongoDB: query for monthSpring Data MongoDB:查询月份
【发布时间】:2016-08-09 12:10:24
【问题描述】:

我正在使用 Spring-boot 开发 webApp,我正在寻找创建查询 findByMonth(int or String month) 但我希望能够使用例如 findByNameAndMonth(String name, month) 或 findByIdAndMonth( ) 是否可以? 日期为 LocalDate 类型。

我有一个像这样的对象:

public final class Alarm {
  @id
  private final String id;
  private final String type;
  // ....
  private final LocalDate date; 

它是一个 mongoRepository:

 public interface AlarmRepository extends MongoRepository<Alarm, String>{
 }

该查询应该给出与该查询相同的结果,例如:

db.alarm.find({ $where : 'return this.date.getMonth() == 5'})

【问题讨论】:

标签: spring spring-data-mongodb


【解决方案1】:

LocalDate 作为 ISODate 存储在 MongoDB 中,因此无法直接访问它的属性(date.month 不起作用,必须使用方法 getMonth())。

这导致使用 Spring Data 中的日期有点棘手。为了解决您的问题,我建议在您的存储库中创建此方法:

List<Alarm> findByDateBetween(LocalDate from, LocalDate to);

但您必须注意边界条件(月初和月底)。

另一种选择是将日期存储为普通对象并通过其属性访问月份,如documentation 中所述。

【讨论】:

    【解决方案2】:

    是的,这是可能的。 Spring Data 期望存储库方法名称中的变量名称相同。例如: public final class Alarm { @id private final String id; private final String type; .... private final LocalDate date;

    然后在您的存储库中,方法名称应如下所示。

    findByIdAndDate(String id, LocalDate date); findByIdAndType(String id, String type);

    【讨论】:

    • 是的,我知道我的问题是做同样的事情,但只是一个月而不是整个日期,就像这个查询 db.alarm.find({ $where : 'return this.date .getMonth() == 5'})
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2018-11-25
    • 2020-10-07
    相关资源
    最近更新 更多