Java 在 JPA 查询上设置 ORDER BY 和 LIMIT 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20849389/
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
Setting ORDER BY and LIMIT clause on JPA Query
提问by daniel0mullins
I'm very, very new to Hibernate and JPA. I want to be able to apply ORDER BY and LIMIT clauses to a Hibernate(?) query, but am coming up empty. NOTE: I inherited this code.
我对 Hibernate 和 JPA 非常非常陌生。我希望能够将 ORDER BY 和 LIMIT 子句应用于 Hibernate(?) 查询,但结果是空的。注意:我继承了此代码。
Here is the current code:
这是当前的代码:
public SomeCoolResponse getSomeCoolResponse(String myId) {
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id";
Query q = getEntityManager().createQuery(queryString);
q.setParameter("id", myId);
List<MyThings> list = q.getResultList();
if(list.size() > 0) {
return list.get(0);
}
return null;
}
Instead of getting an entire list and then just returning the first result (which is the only one we need), I'd like to be able to apply a LIMIT 0,1
clause so that the query will be faster. Also, the query needs to be sorted descending on aThing.created
which is a UNIX timestamp integer.
而不是获取整个列表然后只返回第一个结果(这是我们唯一需要的结果),我希望能够应用一个LIMIT 0,1
子句,以便查询更快。此外,查询需要按aThing.created
UNIX 时间戳整数降序排序。
I've tried altering queryString
like this:
我试过这样改变queryString
:
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id ORDER BY aThing.created LIMIT 0,1";
But Hibernate still returns the entire set.
但是 Hibernate 仍然返回整个集合。
I've looked at using the JPA CriteriaBuilder API, but it hurt my brain.
我看过使用 JPA CriteriaBuilder API,但它伤害了我的大脑。
I'm a total n00b when it comes to this, and any help is greatly appreciated!
在这方面,我完全是 n00b,非常感谢任何帮助!
采纳答案by peter.petrov
I think you need
我想你需要
q.setMaxResults(1);
See also the accepted answer here.
另请参阅此处接受的答案。
How do you do a limit query in HQL?
As to the "order by" clause you may include it in the queryString
.
至于“order by”子句,您可以将其包含在queryString
.
回答by Ebru Yener
The JPQL equivalent to LIMIT start,max is:
等价于 LIMIT start,max 的 JPQL 是:
setFirstResult
and setMaxResults
:
setFirstResult
和setMaxResults
:
q.setFirstResult(start);
q.setMaxResults(limit);