Java JPA 找到最后一个条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2061068/
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-13 03:06:15  来源:igfitidea点击:

JPA find the Last entry

javasqljpa

提问by Roch

I would like to know what's the best way to get the last entry of a table with JPA. In Sql, what I'm looking for would be like:

我想知道使用 JPA 获取表的最后一个条目的最佳方法是什么。在 Sql 中,我正在寻找的是:

select id from table order by id desc limit 1 

I was thinking about model.count() but that sounds more like a hack than a good solution ;)

我在考虑 model.count() 但这听起来更像是一个黑客而不是一个好的解决方案;)

采纳答案by rayd09

You could use a JPQL querythat looks very similar to your query.

您可以使用JPQL query看起来与您的查询非常相似的 。

select t from JpaClass t order by t.id desc

After you establish your Query objectyou could then call

在你建立你的之后,Query object你可以打电话

query.getSingleResult() or call query.setMaxResults(1)

followed by

其次是

query.getResultList()

EDIT: My mistake: Please note mtpettyp's comment below.

编辑:我的错误:请注意下面 mtpettyp 的评论。

Don't use query.getSingleResult() as an exception could be thrown if there is not exactly one row returned - see java.sun.com/javaee/5/…() - mtpettyp

不要使用 query.getSingleResult() 因为如果返回的行不完全是可能会抛出异常 - 请参阅 java.sun.com/javaee/5/...() - mtpettyp

Go with setMaxResults and getResultList.

使用 setMaxResults 和 getResultList。

query.setMaxResults(1).getResultList();

回答by arnoe

The results of query methods can be limited via the keywords firstor top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed.

查询方法的结果可以通过关键字firsttop进行限制,这两个关键字可以互换使用。一个可选的数值可以附加到 top/first 以指定要返回的最大结果大小。如果忽略该数字,则假定结果大小为 1。

JpaClass findFirstByOrderByIdDesc();

referenced by Spring Data JPA docs

Spring Data JPA 文档引用

回答by Michel Fernandes

To the users that opted to use an entityManager, try this:

对于选择使用 entityManager 的用户,请尝试以下操作:

public List<T> findNRows(int n){
        return entityManager.createQuery("from "+entityClass.getSimpleName()+" ORDER BY id DESC",entityClass).setMaxResults(n).getResultList();
}

回答by SkyHigh

I know I'm late to the party, but this might help someone. If you want to fetch the latest entry by created timestamp. (When you don't want to rely on the table id):

我知道我参加聚会迟到了,但这可能会对某人有所帮助。如果您想通过创建的时间戳获取最新条目。(当您不想依赖表 id 时):

YourEntity findFirstByOrderByCreatedTsByDesc();

YourEntity findFirstByOrderByCreatedTsByDesc();