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...
我想在Grails中制作一个简单的测验应用程序。我有问题需要从问题表中选择一个随机行并显示,每次用户提交答案时,问题必须不同。我是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.
我有一个名为QuizController.groovy的控制器类,在控制器中,我有playQuiz(),它应该一次呈现一个名为playQuiz.gsp的gsp页面。
My domain for question is Question which have following
int id String question String answer1 String answer2 String answer3 String answer4 int correctAnswer
我的问题域名是问题,其中有以下int id字符串问题字符串answer1字符串answer2字符串answer3字符串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!
提前致谢!
2 个解决方案
#1
2
Try this, was tested with Grails 2.5.3:
试试这个,用Grails 2.5.3测试:
def randomQuestion = Question.find("from Question order by rand()")
#2
0
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).
这不是很困难。 Hibernate Criteria具有指定第一个结果索引的方法:setFirstResult(int firstResult)和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
您也可以使用HQL
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.
而且您需要使用其他限制才能提出之前提出的问题。
#1
2
Try this, was tested with Grails 2.5.3:
试试这个,用Grails 2.5.3测试:
def randomQuestion = Question.find("from Question order by rand()")
#2
0
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).
这不是很困难。 Hibernate Criteria具有指定第一个结果索引的方法:setFirstResult(int firstResult)和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
您也可以使用HQL
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.
而且您需要使用其他限制才能提出之前提出的问题。