Rajesh Basnet
Rajesh Basnet

Reputation: 3

How do I select a random row from database in grails?

I am trying to make a simple Quiz Application in Grails. I am having problem that i need to select a random row from the question table and display, and each time the user submits the answer, the question must be different. I am new to grails...

I have a controller class named QuizController.groovy and in controller, i have playQuiz() which should render a gsp page named playQuiz.gsp with one question at a time.

My domain for question is Question which have following
int id String question String answer1 String answer2 String answer3 String answer4 int correctAnswer

In database there may be numbers of rows populated with the datas, and i need to take one data at a time in random.

I need help with the data fetching from database in random order.

Thanks in advance!

Upvotes: 0

Views: 1070

Answers (2)

z.eljayyo
z.eljayyo

Reputation: 1289

Try this, was tested with Grails 2.5.3:

def randomQuestion = Question.find("from Question order by rand()")

Upvotes: 4

v.ladynev
v.ladynev

Reputation: 19956

It is not very difficult. Hibernate Criteria has methods to specify the first result index: setFirstResult(int firstResult) and max rows count: setMaxResults(int maxResults).

int rowsCount = getRowsCount();
int randomRowIndex = getRandomNumberLessThan(rowsCount);

criteria.setFirstResult(randomRowIndex);
criteria.setMaxResults(1);

You can use HQL as well

Query query = session.createQuery("from Question");
query.setFirstResult(randomRowIndex);
query.setMaxResults(1);

And you need to use additional restrictions to not ask a question that was asked before.

Upvotes: 0

Related Questions