Search code examples
mysqlrandomsql-order-byebean

How do I pull records RANDOMLY in MySQL using the Ebean ORM?


I have a requirement where I have to pull a random set of records from a MySQL table and this can be achieved by using the RAND() method inside the SQL query as shown below:

SELECT Id
FROM table1
ORDER BY RAND()

However I need to implement the same thing now using the Ebean ORM and after reading through the docs I could not find any reference to the Rand() method. Is there an equivalent in Ebean to this? Or anyway I can replicate the same functionality purely through Ebean only?

Available methods for the orderBy query in Ebean: https://ebean.io/docs/query/orderBy


Solution

  • You would use an orderBy expression:

    .orderBy("RAND()")