-->
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: Random select with Criteria
PostPosted: Tue Oct 03, 2006 6:23 am 
Beginner
Beginner

Joined: Wed Jan 25, 2006 10:18 am
Posts: 28
How do I use Criteria to select n random entities?
Code:
Criteria criteria = ...
criteria.setMaxResults(n);
criteria.addOrder(Order.asc("rand()")); // <-- something like this
return criteria.list();


Top
 Profile  
 
 Post subject:
PostPosted: Tue Oct 03, 2006 3:27 pm 
Regular
Regular

Joined: Tue Sep 26, 2006 11:37 am
Posts: 115
Location: Sacramento, CA
One option is to do the following:

Criteria.setFirstResult(randomNumber) ;
criteria.setMaxResults(4*n);
// select randomingly n entries out of the 4*n returned

You can combine this with
for ( nbLoops ) {
Criteria.setFirstResult(randomNumber) ;
criteria.setMaxResults(10);
// select randomingly from the 10
}

A third mechanism is to have some field that is random. Every time you write a record you write something random to the field. Or you have a process you run over night. Then you sort on the random field.

If this helps ... please rate :)

Marius


Top
 Profile  
 
 Post subject: Re: Random select with Criteria
PostPosted: Sat Oct 03, 2009 1:10 pm 
Beginner
Beginner

Joined: Tue Sep 08, 2009 9:49 am
Posts: 23
Fourth option... create an OrderRandom class:

Do not use this if you are planning to switch your projects DBMS in the future!

Code:
package xy;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Order;

public class OrderRandom extends Order
{
   protected final static String RANDOM = "random()"; //random() generates a random number on PostgreSQL
   private static final long serialVersionUID = 3815371067383546907L;

   public OrderRandom()
   {
      super(null,true);
   }

   @Override
   public String toSqlString(Criteria arg0, CriteriaQuery arg1) throws HibernateException
   {
      return this.toString();
   }
   
   @Override
   public String toString()
   {
      return RANDOM;
   }
}


usage:
Code:
...
criteria.addOrder(new OrderRandom());
...


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.