开发者

Dynamic order by in JPA/Hibernate?

开发者 https://www.devze.com 2022-12-16 10:09 出处:网络
The naive attempt query would look like this: Query query = em.createQuery(\"from org.domain.Resource r where r._parent = ? order by ?\");

The naive attempt query would look like this:

Query query = em.createQuery("from org.domain.Resource r where r._parent = ? order by ?");

This does not work as the parameters should be data and not column names or syntax like ASC or DESC.

What kind of workarounds you have figured out for this dynamic ordering? Con开发者_Go百科catenating the ordering string to the query string is the obvious one but are there any better ones?


This is unfortunately how it must be done with JPA.

I do however vaguely remember having used numbered parameters (?1, ?2..) for ordering with native queries (em.createNativeQuery) on Hibernate (but I could be wrong). Anyway another solution (if you are using JPA2 or Hibernate) is to use the criteria API

0

精彩评论

暂无评论...
验证码 换一张
取 消