Select random row

I want to select any single random
I think this loads all the list and returns the first one.
dataManager.load(Organizations.class).all().one();
I need it to be just be a random one.

Thank you for the help !!

This loads the first one returned by the database (using SQL limit 1):

dataManager.load(Organizations.class).all().maxResults(1).one();

Performance would be an issue but one way to do it would be to load everything into a List, get the size of the list, then generate a random number between 0 and size of list, and use that to pull that entry out by index.

Thanks you both for your reply.

Can you guys give me your opinion on this approach?

public Organization getRandom() {
        Integer rowCount = dataManager
                .loadValue("select count(e.id) from app_Organization e", Integer.class).one();
        return dataManager.loadValue("select e from app_Organization e", Organization.class)
                .firstResult(new Random().nextInt(rowCount + 1)).maxResults(1).one();
    }

Looks good to me :slight_smile:

1 Like