JPQL ORDER BY clause with parameter

2020-02-26 05:49发布

I'm trying to write a JPQL Query with an ORDER BY clause:

query = "SELECT c FROM item ORDER BY c.name ASC"

I would like to set an "order" parameter, whose value would be either "ASC" or "DESC":

query = "SELECT c FROM item ORDER BY c.name :order"

And then in my implementation:

query.setParameter("order", "ASC");

This is when I get an Hibernate error:

org.hibernate.HibernateException: Errors in named queries

Any idea on what I'm doing wrong? Thanks!

4条回答
虎瘦雄心在
2楼-- · 2020-02-26 06:38

If you want to use named queries here, you'd need two of them (named queries are static and you can't use ASC and DESC as parameter as pointed out by @Mark).

查看更多
乱世女痞
3楼-- · 2020-02-26 06:49

I suppose right way is using ORDER BY clause of Criteria API

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Country> q = cb.createQuery(Country.class);
Root<Country> c = q.from(Country.class);
q.select(c);
q.orderBy(cb.asc(c.get("currency")), cb.desc(c.get("population")));
查看更多
▲ chillily
4楼-- · 2020-02-26 06:50

The "ASC" or "DESC" can't be a query parameter. You could use string concatenation instead.

query = "SELECT c FROM item ORDER BY c.name " + sortOrder;

You should validate that the contents of sortOrder can only be ASC or DESC and does not come directly from the user.

查看更多
老娘就宠你
5楼-- · 2020-02-26 06:53

Instead of writing twice a named Query containing an 'order by' clause, you can implement your DAO this way :

public List<MyEntity> findByAttribute(boolean desc,...){
    TypedQuery<MyEntity> q = em.createNamedQuery(...
    q.setParameter(...
    List<MyEntity> result = q.getResultList();
    if(desc){
        Collections.reverse(result );
    }
    return result;
}
查看更多
登录 后发表回答