0

I'm developing a web application using asp.net Mvc 2 and NHibernate, and I'm paging data (products in a category) in my page, but this data are random, so, I'm using a HQL statement link this:

string hql = "from Product p where p.Category.Id=:IdCategory order by rand()";

It's working fine, but when I page, sometimes the same product appears in the first, second, etc... pages because it's order by rand().

Is there any way to make a random order by fixed by period (time internal) ? Or any solution ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194

2 Answers2

4

Seed the random number generator:

order by rand(123)

I would suggest using a session-scoped random number as your seed. That way, the page doesn't suddenly re-sort for a single user, but it's still be sorted differently for every user.

Dolph
  • 49,714
  • 13
  • 63
  • 88
  • can I use a SessionId ? Or use Random object to get a number and put on Session and use it! well.. i'll try this! Thanks – Felipe Oriani May 26 '10 at 18:02
  • You can use the session ID but you need to convert it to a number first (if it's not already): `Integer.parseInt(sessionId, radix)`. – Dolph May 26 '10 at 18:50
  • thanks man, i think that I'll to cache a number by time (1 or 5 minutes) and use it... thats great! Cheers – Felipe Oriani May 27 '10 at 11:49
1

I don't see why you're deliberately randomising the data. If there's no particular order you want them in, why not just order by the primary key?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hi Jon, it's a advertisement product page, and I'd like to randomize the records to the users... because if i didn't do that, the same products are on the firts page always! – Felipe Oriani May 26 '10 at 17:36
  • In that case you need to provide some stable ordering based on something which stays constant for each user. Do you have a cookie of any kind there? – Jon Skeet May 26 '10 at 17:45
  • Well, I dont have any cookie or session. But I can rand it and put on Session! – Felipe Oriani May 26 '10 at 18:03