Random select rows via JPA

后端 未结 2 478
闹比i
闹比i 2020-12-16 17:35

In Mysql,

SELECT id FROM table ORDER BY RANDOM() LIMIT 5

this sql can select 5 random rows. How to do this via JPA Query (Hibernate as pro

相关标签:
2条回答
  • 2020-12-16 18:25

    Only the functions defined in the specification are guaranteed to be supported by all JPA providers and RAND or RANDOM aren't. So I don't think that you can do it in JPQL.

    However, it would be possible in HQL (the order by clause in HQL is passed through to the database, so you can use any function):

    String query = "SELECT o.id FROM Order o ORDER BY random()";
    Query q = em.createQuery(query);
    q.setMaxResults(5);
    

    But, I repeat:

    1. This may not work with another database.
    2. This may not work with another JPA provider.
    0 讨论(0)
  • 2020-12-16 18:35

    Try calculating the random beforehand and construct your JPQL/HQL/native query with the pre-calculated random value.

    0 讨论(0)
提交回复
热议问题