开发者

Howto get a random object from DB?

开发者 https://www.devze.com 2023-03-25 16:54 出处:网络
For more dynamism, I would like to add a random part on my app. Here is what I would have done in other techs, and what is not working in play :

For more dynamism, I would like to add a random part on my app. Here is what I would have done in other techs, and what is not working in play :

long id = JPA.execute("select id from Realisation r order by RANDOM() LIMI开发者_开发问答T 1");

And here is the stack :

unexpected token: LIMIT near line 1, column 55

Comments :

  • Either in app or database, makes no difference to me.
  • About hundred "realisations" in database.
  • All I need is there ID, no need for full object.
  • MySQL database behind it all.

EDIT

After a little investigation, here is how I've done it :

  • Define jpa.dialect in application.conf : jpa.dialect=org.hibernate.dialect.MySQLDialect
  • Fetch a complete object instead of just id with classic Model utilities :

Realisation r = Realisation.find("order by RAND()").first();


After a little investigation, here is how I've done it. Define jpa.dialect in application.conf :

jpa.dialect=org.hibernate.dialect.MySQLDialect

Fetch a complete object instead of just id with classic Model utilities :

Realisation r = Realisation.find("order by RAND()").first();

Not the best way possible, since I only need the ID and not the complete object. Anyway, I have no other solution. If anyone has one for just the ID I will take it.


There is no "limit" clause in JPQL, what you need is paging. You can use Query.setMaxResults instead if this is a JPQL query, which is not entirely clear in the post.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号