<?php
use PHPSnippets\Db\Entity\Test;
$query = $entityManager->createQuery('SELECT MAX(t.id) FROM ' . Test::CLASS . ' t');
// count can be cached if value doesn't change regularly
$maxId = (int) $query->getSingleScalarResult();
$rand = rand(1, $maxId);
echo 'random id = ' . $rand . ' of max id = ' . $maxId . PHP_EOL;
// In theory, the table row of former max id could be deleted by another request at this point
$qb = $entityManager->createQueryBuilder();
$qb->select('t')
->from(Test::CLASS, 't')
// greater or equal in case of deleted ids
->where($qb->expr()->gte('t.id', $rand))
->setMaxResults(1);
$entity = $qb->getQuery()->getSingleResult();
echo 'found: ' . $entity->id . ', ' . $entity->name;