Julia
Julia

Reputation: 1237

How to avoid hibernate default order by id?

I make this query:

String query = FROM Account acc WHERE acc.id = ? OR acc.id = ? or acc.id = ?...

I have array of ids:

long[] accountIds= {327913,327652,327910,330511,330643};

Then I make

getHibernateTemplate().find(query, accountIds);

I see that the list of accounts I get back from this query is:

327652,327910,327913,330511,330643, obviously , ordered by id.

Any chance I get it back in the order I wrote the ids?

Will appreciate all the help

Upvotes: 0

Views: 5781

Answers (4)

user207421
user207421

Reputation: 310883

You can only order by column values returned by the query, in a sequence defined by the data type . Wouldn't it be better to pre-order the IDs you supply, and order the query result by ID, so they come out in the same order?

Upvotes: 0

PVR
PVR

Reputation: 2524

It is not possible to fetch results by providing any entity in OR Query or Restrictions.in(). As by deafult when you fire this kind of query it will search for the results id wise. So it will give you results id wise only. You can change the order by using Criteria either in asc or desc. And if you want to have results as per you enter id, then second answer is the only option.

Upvotes: 0

Matin Kh
Matin Kh

Reputation: 5178

You may want to use Criteria and its addOrder.

Something like this:

DetachedCriteria cr = DetachedCriteria.forClass(entityClass);
//Add expressions or restrictions to your citeria
//And add your ordering
cr.addOrder(Order.asc("yourID"));
List<T> ls = getHibernateTemplate().findByCriteria(cr);
return ls;

Upvotes: 2

Ilya
Ilya

Reputation: 29693

You can't do it on query level.
You can sort after loading from db, something like this

   long[] accountIds= {327913,327652,327910,330511,330643};
   List<Account> afterHql = getHibernateTemplate().find(query, accountIds);
   List<Account> sortedList = new ArrayList<Acount>();
   for (long id : accountIds)
   {
       for (Account account : afterHql)
       {
           if (account.getId() == id)
           {
               sortedList.add(account);
           }
       }
   }

Upvotes: 1

Related Questions