Hibernate Criteria API: get n random rows

前端 未结 5 1812
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 11:06

I can\'t figure out how to fetch n random rows from a criteria instance:

Criteria criteria = session.createCriteria(Table.class);
criteria.add(Restrictions.e         


        
5条回答
  •  天涯浪人
    2020-12-03 11:31

    First of all, be aware that there is no standard way to do this in SQL, each database engine uses its own proprietary syntax1. With MySQL, the SQL statement to get 5 random rows would be:

    SELECT column FROM table
    ORDER BY RAND()
    LIMIT 5
    

    And you could write this query in HQL because the order by clause in HQL is passed through to the database so you can use any function.

    String query = "SELECT e.attribute FROM MyEntity e ORDER BY RAND()";
    Query q = em.createQuery(query);
    q.setMaxResults(5);
    

    However, unlike HQL, the Criteria API currently doesn't support ORDER BY Native SQL (see HHH-2381) and in the current state, you would have to subclass the Order class to implement this feature. This is doable, refer to the Jira issue, but not available out of the box.

    So, if really you need this query, my recommendation would be to use HQL. Just keep in mind it won't be portable.

    1 Other readers might want to check the post SQL to Select a random row from a database table to see how to implement this with MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle.

提交回复
热议问题