How to do a random search using JPQL script in JPA2

0

The idea is basically to look for an X number of persisted entities in a random way, and these entities can not be repeated. The question is, can you perform this type of search by creating and executing a JPQL script ?, or is it necessary to implement a logic in JAVA?

Example

public Jogo gerarJogo(EntityManager em)
{
   Jogo jogo = new Jogo();
   public String query = //query 
   List<Pergunta> perguntas =  em..createQuery(query).getResultList();
   jogo.setPerguntas(perguntas);
   return jogo;
}

If you need to implement the logic in java, you do not need the algorithm, but I need more technical information like, if necessary, to search the registry with lesser or greater id, among others.

    
asked by anonymous 02.10.2014 / 16:23

1 answer

1

I'll respond as if you were working mySQL.

The problem is that RANDOM is not covered by the JPA specification. My suggestion is that you do a native query +/- like this:

SELECT id FROM tabela ORDER BY RAND() LIMIT quantidadeDeRegistros

Then, with these records, make a jpaQL with IN :

SELECT p FROM Pergunta p WHERE p.id IN :ids

    
02.10.2014 / 17:17