methode JEE implementation

时间:2016-04-25 09:12:23

标签: jpa

I implemented a method that allows me to generate a test ( entire of question ) automatically but the problem is : the method will obviously take the number of random questions but also the category of questions generated (I have a entié category and therefore a table too) I don't know where i will put the category in query. and secondly RANDOM() is not taked by JPQL what can i do ?

schema of the DataBase

public List<Question> prepareRandomTest(int number_of_questions, Categorie      categorie){ 
      String jpql = "SELECT q FROM Question q ORDER BY RANDOM() LIMIT "+number_of_questions  ;
     Query query = entityManager.createQuery(jpql);
      return query.getResultList();
    }

1 个答案:

答案 0 :(得分:1)

您正在尝试使用 Java持久性查询语言,因此您的解决方案不会考虑RANDOM。使用Native查询并从本机sql字符串构建Query,Native查询只是一个没有Entity对象引用的普通sql语句(如Question)。通过这种方式,可以轻松读取像RANDOM等常见的sql关键字。

Native Query Tutorial

而非使用

String jpql = "SELECT q FROM Question q ORDER BY RANDOM() LIMIT "+number_of_questions  ;

使用:

"SELECT * FROM question where category="+category+" ORDER BY RANDOM() LIMIT "+number_of_questions;

其他建议: 从代码中的“Enum”获取类别字符串,以匹配数据库类别列中的字符串值。