JPA找到最后一个条目 [英] JPA find the Last entry
问题描述
我想知道用JPA获取表的最后一个条目的最佳方法是什么. 在Sql中,我正在寻找的将是:
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:
select id from table order by id desc limit 1
我当时在考虑model.count(),但这听起来像是hack,而不是一个好的解决方案;)
I was thinking about model.count() but that sounds more like a hack than a good solution ;)
推荐答案
您可以使用看起来与查询非常相似的JPQL query
.
You could use a JPQL query
that looks very similar to your query.
select t from JpaClass t order by t.id desc
建立Query object
后,您可以致电
query.getSingleResult() or call query.setMaxResults(1)
跟着
query.getResultList()
我的错误:请注意下面的mtpettyp评论.
My mistake: Please note mtpettyp's comment below.
不要使用query.getSingleResult()作为例外,如果 没有完全返回一行-请参见java.sun.com/javaee/5/…() -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
使用setMaxResults和getResultList.
Go with setMaxResults and getResultList.
query.setMaxResults(1).getResultList();
这篇关于JPA找到最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!