3

How do I accomplish this custom sort by field feature available in MySQL in hibernate?

select * from pet order by field(species, 'cat', 'dog', 'bird');

For some business reason, I need to enforce a custom ordering.

PS -I am new to hibernate.

pranay
  • 444
  • 1
  • 7
  • 20
  • Not sure if we have something same in hibernate but below links describes all types of sort in hibernate http://www.baeldung.com/hibernate-sort – LearningPhase Apr 07 '16 at 16:11
  • Possible duplicate of [SQL multiple column ordering](http://stackoverflow.com/questions/2051162/sql-multiple-column-ordering) – docksteaderluke Apr 07 '16 at 17:27

2 Answers2

0

I ended up writing an HQL like this

commaDelimitedSpecies = "'cat', 'dog', 'bird'";
orderBySpecies = " ORDER BY FIELD(species, " + commaDelimitedSpecies + ")  DESC";
Query q = getSession().createQuery("FROM PetModel pet" + orderBySpecies);
pranay
  • 444
  • 1
  • 7
  • 20
0

With Spring HibernateDAO:

getHibernateTemplate().findByNamedParametersQuery(
"FROM MyEntity me WHERE me.id IN :ids ORDER BY FIELD(id, :ids)", new String[] {"ids"}, new Object[] {uuidList.toArray()},uuidList.size()
);

Note: getHibernateTemplate returns an instance of org.springframework.orm.hibernate3.HibernateTemplate

Christoph
  • 3,980
  • 2
  • 40
  • 41