There is a table in the MySQL database. You need to select one random entry and get an entity object at the output.

I tried to do it like this:

Entity getRandomEntity() { int rand = new Random().nextInt(count); Session session = sessionFactory.getCurrentSession(); return (Entity) session.createQuery("from Entity where id = :rand") .setParameter("rand", rand).getSingleResult(); } 

But it does not work, because records in the database are sometimes deleted and, accordingly, id have gaps.

What can be done here?

  • You can number all entries - Roman C

2 answers 2

LIMIT can be restricted

 session.createQuery("FROM Entity").setFirstResult(rand).setMaxResults(1) 
  • Indeed it works that way. Well and at calculation of rand it is necessary to use of course the maximum id, but not the number of records. Thank you - SoulDrake
  • @SoulDrake id has nothing to do with it, the number of records in the table is important. You can have a maximum id equal to a million, and there will be only 2 records in the database, if you make setFirstResult (1000000), you will not get anything. - Vladimir Yarovoy
  • And, damn, for sure, in my original version I had to take max, because I was looking for it there, but here it is necessary by quantity, I got confused a little)) Thanks again - SoulDrake

Like this:

 session.createQuery("select id from Entity id order by rand()") .setMaxResults(1) .list()