简体   繁体   中英

mysql order by field equivalent in hibernate

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.

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM