简体   繁体   English

Spring JPA存储库最近的日期

[英]Spring JPA Repository closest Date

I have an entity (id, created_date). 我有一个实体(id,created_date)。 I want to create a method in my JPARepository that returns the closest row from now. 我想在我的JPARepository中创建一个方法,该方法返回从现在开始最接近的行。 CreatedDate is a ZonedDateTime. CreatedDate是一个ZonedDateTime。 I created next methods (the parameter is ZonedTimeDate.now()): 我创建了下一个方法(参数为ZonedTimeDate.now()):

findTopByCreatedDateBefore (returns first created row) findTopByCreatedDateBefore (返回第一个创建的行)

findFirstByCreatedDateBefore (returns first created row (why the same?)) findFirstByCreatedDateBefore (返回第一个创建的行(为什么一样?))

findTopByCreatedDateBeforeOrderByCreatedDateDesc (returns last created row) findTopByCreatedDateBeforeOrderByCreatedDateDesc (返回最后创建的行)

findFirstByCreatedDateBeforeOrderByCreatedDateDesc (returns last created row (why the same?)) findFirstByCreatedDateBeforeOrderByCreatedDateDesc (返回上一个创建的行(为什么一样?))

The last two return what I want but is it the best way to use them? 最后两个返回我想要的东西,但这是使用它们的最佳方法吗? Why are the first two return the same result? 为什么前两个返回相同的结果?

Because the keywords Top and First are both limiting the results to the optional number following it defaulting to 1. So they only define the number of elements to return, not an implicit ordering — mostly because of the fact that no ordering exists, unless you explicitly specify it. 因为关键字TopFirst都将结果限制为默认值1之后的可选数字,所以它们定义要返回的元素数,而不是隐式排序-主要是因为不存在任何排序,除非您明确指定指定它。

What top and first can't be defined without any ordering semantics as most stores don't guarantee any kind of ordering of the result unless you specify sorting options. 没有任何排序语义就不能定义topfirst ,因为除非您指定排序选项,否则大多数商店都不保证结果的任何排序。 Thus, the order of the elements might even vary for each method invocation. 因此,每个方法调用的元素顺序甚至可能有所不同。

So in the examples you gave, the first two methods restrict the result to exactly one argument. 因此,在您给出的示例中,前两种方法将结果限制为一个参数。

我只是将PageRequest作为findAll的参数传递,其中page为1,pageSize为1,顺序为DESC “ createdDate”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM