获取对给定年份有效的记录的 Spring 数据(具有 fromDate、toDate 字段)
Posted
技术标签:
【中文标题】获取对给定年份有效的记录的 Spring 数据(具有 fromDate、toDate 字段)【英文标题】:Spring data getting records valid for given year (with fields fromDate, toDate) 【发布时间】:2019-03-11 22:07:00 【问题描述】:我正在尝试使用 JPA 存储库从 DB 中过滤一些记录。
我得到了一个带有字段的实体:
@Column(name = "from_date", nullable = false)
private ZonedDateTime fromDate;
@Column(name = "to_date", nullable = true)
private ZonedDateTime toDate;
我需要选择给定年份发生的所有记录(例如 2018 年)。 棘手的部分是:如果 'from_date' 来自 2017 年,但 'to_date' 是 ie。 2019 年,我想收录那张唱片。
你能告诉我一些想法,如何解决吗?是否有可能只用一种方法得到它? 如果可能的话,我想使用查询方法。
此刻,我发明了方法:
List<ManualCorrection> findByFromDateGreaterThanEqualAndFromDateLessThanAndToDateGreaterThanEqual(ZonedDateTime yearStart,ZonedDateTime yearEnd, ZonedDateTime yearStart2);
但是这并没有给我所有我感兴趣的记录。
感谢您的帮助!
【问题讨论】:
【参考方案1】:这个应该找到所有具有toDate >= yearStart
和fromDate <= yearEnd
的ManualCorrection
实体,这似乎是您正在寻找的。p>
List<ManualCorrection> findByToDateGreaterThanEqualAndFromDateLessThanEqual(
ZonedDateTime yearStart,
ZonedDateTime yearEnd
);
【讨论】:
请连同您的代码一起解释您的答案。它也将有助于未来的读者。 很抱歉 Jens - 我的错误,我在其他地方遇到了错误。您的回答从一开始就很好,非常感谢您!我不想再打扰你了,但我想知道是否可以扩展该方法,并将字段“toDate”中的“null”视为“无限”(永无止境)?简单的解决方案,例如: findByToDateIsNullOrToDateGreaterThanEqualAndFromDateLessThanEqual 听起来不像是解决方案。目前我只是获得了另一种方法来处理这种记录,但我还是要加入结果。 您可以使用@Query
注释和一些( .... or x IS NULL)
来实现。【参考方案2】:
你应该看看the reference documentation。解释得很好。
在你的情况下,我认为你不能使用 between 因为你需要传递两个参数
Between - findByStartDateBetween … 其中 x.startDate 在 ?1 和 ?2 之间
在您的情况下,请查看使用 LessThan
或 LessThanEqual
与 GreaterThan
或 GreaterThanEqual
的组合
GreaterThan/GreaterThanEqualLessThan - findByEndLessThan … where x.start
LessThanEqual findByEndLessThanEqual … 其中 x.start
GreaterThan - findByStartGreaterThan ... where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … 其中 x.end>= ?1
您可以使用运算符And
和Or
将两者结合起来。
您还可以使用@Query
编写自定义查询
@Query(value = "from EntityClassTable t where yourDate BETWEEN :yearStart AND :yearEnd")
public List<EntityClassTable> getAllBetweenDates(@Param("yearStart")Date yearStart,@Param("yearEnd")Date yearEnd);
希望这会对您有所帮助。谢谢:)
【讨论】:
是的,伙计,我确实看过文档,但是我的问题出在其他地方。以免说,我需要 2018 年的记录。在 db 中,我得到了一些日期从 2017 年到 2022 年的记录——它在 2018 年占有一席之地,所以我想要这个。但我也有一些 dateFrom 2011 和 toDate 2017,我不想要这个。这就是 egzamples 中的简单方法失败的地方。此外,它可能变化不大,但日期有天、月、年和时间。以上是关于获取对给定年份有效的记录的 Spring 数据(具有 fromDate、toDate 字段)的主要内容,如果未能解决你的问题,请参考以下文章