java 通过 JPA 随机选择行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2459119/
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
Random select rows via JPA
提问by Ke.
In Mysql,
在 MySQL 中,
SELECT id FROM table ORDER BY RANDOM() LIMIT 5
this sql can select 5 random rows. How to do this via JPA Query (Hibernate as provider, Mysql database)?
这个 sql 可以选择 5 个随机行。如何通过 JPA 查询(Hibernate 作为提供者,Mysql 数据库)执行此操作?
Thanks.
谢谢。
回答by Pascal Thivent
Only the functions defined in the specification are guaranteed to be supported by all JPA providers and RANDor RANDOMaren't. So I don't think that you can do it in JPQL.
只有规范中定义的函数才能保证得到所有 JPA 提供者的支持,RAND或者RANDOM不支持。所以我不认为你可以在 JPQL 中做到这一点。
However, it would be possible in HQL (the order by clause in HQL is passed through to the database, so you can use any function):
但是,在 HQL 中是可能的(HQL 中的 order by 子句传递到数据库,因此您可以使用任何函数):
String query = "SELECT o.id FROM Order o ORDER BY random()";
Query q = em.createQuery(query);
q.setMaxResults(5);
But, I repeat:
但是,我再说一遍:
- This may not work with another database.
- This may not work with another JPA provider.
- 这可能不适用于其他数据库。
- 这可能不适用于其他 JPA 提供程序。
回答by Bozho
Try calculating the random beforehand and construct your JPQL/HQL/native query with the pre-calculated random value.
尝试预先计算随机数并使用预先计算的随机值构建您的 JPQL/HQL/本机查询。

