简体   繁体   English

从数据库表中随机选择实体?

[英]Randomly select Entites from database table?

How would I randomly select rows from a database table? 如何从数据库表中随机选择行? I'm using JPA and would like to use the Criteria API if possible. 我正在使用JPA,并且在可能的情况下希望使用Criteria API。 I'm aware there is an SQL equivalent, something like: 我知道有一个SQL等效项,例如:

    SELECT TOP 5 Id, Name FROM mNames
    ORDER BY NEWID()

But how would I do this with JPQL and the Criteria API? 但是,我该如何使用JPQL和Criteria API做到这一点? Possibly, with a NativeQuery? 可能是使用NativeQuery吗? Is there a better way? 有没有更好的办法?

If all you need is a single random row, then you can do something like this: 如果您只需要一个随机行,则可以执行以下操作:

//random is instance of java's Random class, and numberOfRows is total number of rows in the table
long rowIndex = random.nextLong()%numberOfRows;

TypedQuery typedQuery = ...;
typedQuery.setFirstResult(rowIndex);
typedQuery.setMaxResults(1);

I didn't test the code but you should get the idea. 我没有测试代码,但您应该明白这一点。

如果您的实体的主键不是一个任意数字,而是某个功能,那么您最好选择随机创建一个有效密钥,然后查询特定的行,这是快速的操作,而不是仅仅执行可能的大量行过滤掉所有的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM