Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL ORDER BY clause with parameter

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!

like image 807
Pierre Duplouy Avatar asked Sep 01 '10 08:09

Pierre Duplouy


People also ask

Which of the following clauses are supported in JPQL?

JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.

Which methods should be used for pagination with JPQL?

For all JPA query objects (except for native SQL queries), you would use pagination through the setMaxResults(int) and setFirstResult(int) methods.

What is the difference between HQL and JPQL?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

How do you write orderBy in JPA?

With JPA Criteria – the orderBy method is a “one stop” alternative to set all sorting parameters: both the order direction and the attributes to sort by can be set. Following is the method's API: orderBy(CriteriaBuilder. asc): Sorts in ascending order.


1 Answers

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.

like image 118
Mark Byers Avatar answered Sep 18 '22 07:09

Mark Byers