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.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top