Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of 10 random unique objects with Hibernate?

Does anyone have HQL query on how to get list of 10 random unique objects from the database?

It should be done in database not in application. I'd like to get something that has better performance than my current solution which pretty much makes 10 requests to get the list filed up.

like image 712
MatBanik Avatar asked Dec 11 '10 03:12

MatBanik


1 Answers

HQL would be something like:

session.createQuery("select o from Object o order by rand()")
   .setMaxResults(10)
   .list()

The rand() is passed through to the database so replace this with whatever function your database uses.

like image 54
Damo Avatar answered Sep 20 '22 21:09

Damo