JPQL ORDER BY clause with parameter

Pierre Duplouy picture Pierre Duplouy · Sep 1, 2010 · Viewed 26.6k times · Source

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!

Answer

Mark Byers picture Mark Byers · Sep 1, 2010

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.