2016-04-25 278 views
1

我有一個實體問題,我想生成數據庫我的問題隨機隨機生成的問題:我要生成與JPQL隨機問題查詢

@Override 
public List<Question> prepareRandomTest(int number_of_questions, Categorie categorie){ 

      String jpql = "SELECT q FROM Question q where q.categorie=:categorie"; 
      Query query = entityManager.createQuery(jpql); 
      query.setParameter("categorie", categorie); 
      query.setMaxResults(number_of_questions); 
      return query.getResultList(); 

} 

這是我的主要

Categorie categorie; 
categorie=GestionCategorieDelegate.doFindCategorieById(1); 

List<Question> questions=new ArrayList<>(); 
    questions=GestionTestDelegate.doPrepareRandomTest(1, categorie); 
    for (Question q : questions) 
    { 

     System.out.println(q); 
    } 
} 
+2

那麼什麼是你的問題? –

+0

我希望問題會隨機顯示 – Daly

+2

也許這有幫助嗎? http://stackoverflow.com/questions/2459119/random-select-rows-via-jpa – eol

回答

1

您可以在列表中使用Collecions.shuffle

所以在doPrepareRandomTest而不是

return query.getResultList(); 

你可以把

List<Questions> result = query.getResultList(); 
Collections.shuffle(result); 
return result; 
+0

剛剛開始寫相同的答案。在網絡中很難理解,但似乎JPQL不再支持'random()',所以使用java進行隨機隨機播放將是一種好方法!帕維爾+10擊敗我。 –

+0

@Paweł.Ch我試過你的解決方案,但問題不是隨機生成的,它總是第一個問題產生 – Daly