Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random select rows via JPA

In 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)?

Thanks.

like image 260
Ke. Avatar asked Mar 17 '10 00:03

Ke.


1 Answers

Only the functions defined in the specification are guaranteed to be supported by all JPA providers and RAND or RANDOM aren't. So I don't think that you can do it in 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):

String query = "SELECT o.id FROM Order o ORDER BY random()";
Query q = em.createQuery(query);
q.setMaxResults(5);

But, I repeat:

  1. This may not work with another database.
  2. This may not work with another JPA provider.
like image 100
Pascal Thivent Avatar answered Sep 24 '22 03:09

Pascal Thivent