I would like to get a random object from database only with GORM, without using database specific code.
Currently I'm using this:
Tag.executeQuery("from Tag order by rand()", [max: Tag.count()])
But I'm not satisfied with that because I'm using mysql's rand() function. Some people recommend to get all IDs, then choose a random one, and then query for the whole object, but I don't want two queries.
Is there a GORM way to do this? If not pure GORM, then maybe Hibernate solution would do the trick.
(I've seen this question here Grails GORM to return random rows from table?, but it does not help :))
You can first get a random offset, put max:1
and then execute your query with these pagination parameters!
(Note: you will have to do a count()
on your table first but it isnt a very costly operation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With