Get random strings using JPQL

Is it possible to use JPQL to get random strings? For example, in SQL Server, I would use: select * from myTable, where columnName = 4 order by newid ()

Thanks Rod

+3
source share
2 answers

This is what I use. First, I get the number of rows for the object, and then limit the results of the fetch request to a random string. This includes two queries, so if this is a problem for you, you may want to look at your own queries. If not here is the code I'm using:

 public <T> T randomEntity(EntityManager em, Class<T> clazz) {
      Query countQuery = em.createQuery("select count(id) from "+clazz.getName());
      long count = (Long)countQuery.getSingleResult();

      Random random = new Random();
      int number = random.nextInt((int)count);

      Query selectQuery = em.createQuery("from "+clazz.getName());
      selectQuery.setFirstResult(number);
      selectQuery.setMaxResults(1);
      return (T)selectQuery.getSingleResult();
 }
+4
source

As of today (April 9, 2010), JPQL does not support random ordering.

+1
source

Source: https://habr.com/ru/post/1723583/


All Articles