Jbisgood9999999
Jbisgood9999999

Reputation: 253

Sorting by hibernate with special arrangement

I am now facing a problem about Sorting the result getting from DB. I want to sort by ASC but I want to make an exception , "OTHERS". So the selection "Others" will be at last of the selection. How can i implement this? So, the ComboBox List will like this :

AA
BB
CC
DD
......
......
XX
YY
ZZ
Others

Code i tried:

public List<Testing> findAll() {
    Criteria criteria = getSession().createCriteria(Testing.class);
    criteria.addOrder(Order.asc("TestingString"));
    return (List<Testing>) criteria.list();
}

By using this coding, "Others" will between "OO" and "PP". It is a bad way to show the selection "Others".

Upvotes: 0

Views: 38

Answers (2)

StanislavL
StanislavL

Reputation: 57381

On hibernate you can define a @Formula annotated field where the value is SQL representation of the order. Then use the @Formula annotated field in your sort.

The expression could be

CASE columnName
   WHEN 'Other' THEN 'zzzzzzzzzzzzzz"
   ELSE columnName
END

Upvotes: 0

Tony Vu
Tony Vu

Reputation: 4361

No straightforward way with Hibernate, but you can totally do that in your code. I think of 2 ways:

  1. Do not keep Others in database. Retrieve the sorted list from DB and then add Others to the last of the list manually in your java code.
  2. Keep Others in DB, retrieve all as per normal without even sorting and then call Collections.sort(resultList, comparator) where comparator is your custom comparator in which it compares strings alphabetically but always put Others as biggest value. That will return list you want.

Upvotes: 1

Related Questions