-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Retrieving a single random item?
PostPosted: Fri Mar 03, 2006 2:08 am 
Newbie

Joined: Fri Mar 03, 2006 12:42 am
Posts: 1
I'm using NHibernate with MS SQL Server, and currently am retrieving a random item of a class using this method:

First I find the number of rows in the class table which satisfy my search conditions. Standard SQL: "SELECT COUNT(*) FROM table WHERE conditions".

Next I select a random number between 0 and n-1, where n is the number of rows.

Then I request the id column of that row: "SELECT TOP 1 id FROM table WHERE NOT IN (SELECT TOP index-1 id FROM table)". This last would be a lot easier with a LIMIT clause, but MSSQL doesn't support that.

Finally, I use NHibernate to get the item based on the returned ID.

This is two queries, plus what NHibernate does, for each random item I want; somebody please tell me there's a better way!


Top
 Profile  
 
 Post subject: SetMaxResults
PostPosted: Fri Mar 03, 2006 3:37 am 
Regular
Regular

Joined: Tue Jan 03, 2006 7:21 am
Posts: 85
Once you have the random number you can ask NHibernate to select just that record. You can achieve this by calling
SetFirstResult and SetMaxResults on the IQuery interface. After that when you call IQuery.UniqueResult it will return just one entity (you will have to use the correct Order By)


Top
 Profile  
 
 Post subject:
PostPosted: Sat Mar 04, 2006 5:37 am 
Newbie

Joined: Wed Jan 25, 2006 10:53 pm
Posts: 9
You should be able to do a Native Sql call, i.e session.CreateSqlQuery with a query like....

SELECT TOP 1 {cat.*}
FROM cats {cat}
ORDER BY NEWID()

The order by NEWID gives you a random row each time, don't know how database effiicent it is though.....

Tim


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.