Java Spring Data - 从表中获取最后一条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50871759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:51:16  来源:igfitidea点击:

Spring Data - get last record from the table

javaspringspring-data-jpaspring-data

提问by k13i

I'm using Spring Data JPA and I would like to retrieve the last record from Settingstable.

我正在使用 Spring Data JPA,我想从Settings表中检索最后一条记录。

I have SettingsRepositorywith standard methods implemented by Spring Data. How to write a method (or a query) to retrieve last row from the given table?

我有SettingsRepositorySpring Data 实现的标准方法。如何编写方法(或查询)以从给定表中检索最后一行?

interface SettingsRepository extends JpaRepository<Settings, Long> {
    // ?
}

采纳答案by Lemmy

You should use findTopByOrderByIdDesc()

你应该使用 findTopByOrderByIdDesc()

This is called named query, you can check the documentation

这称为命名查询,您可以查看文档

回答by FrederikVH

There is no specific function to get the last record.

没有特定的函数来获取最后一条记录。

You can, however, order in reverse (DESC on ID, for example - assuming there's an ID) and get the first record.

但是,您可以反向排序(例如,ID 上的 DESC - 假设有一个 ID)并获得第一条记录。

EDIT: As per @MountainKing's suggestion in the comments below, you can use findTopByOrderByIdDesc()

编辑:根据@MountainKing 在下面评论中的建议,您可以使用 findTopByOrderByIdDesc()