Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JPA dynamic order by clause

843830Aug 7 2008 — edited Oct 8 2008
I need to dynamically build the order by clause of my query.

I tried this:
<named-query name="list">
  <query>
    <![CDATA[
      SELECT p FROM Person p
      ORDER BY :orderby
    ]]>
  </query>
</named-query>

@SuppressWarnings("unchecked")
public List<Person> list(String sort) {

  Query query = getEntityManager().createNamedQuery("list");
  query.setParameter("orderby", sort);
  return query.getResultList();
}
But at runtime it throws an exception:
com.microsoft.sqlserver.jdbc.SQLServerException: 
L'elemento SELECT identificato da ORDER BY 1 include una variabile nell'espressione che identifica la posizione di una colonna. 
Le variabili sono consentite solo nell'ordinamento in base a un'espressione che fa riferimento a un nome di colonna.
The translation of the italian message is something like:
The SELECT element identified by ORDER BY 1 includes a variable that identifies the position of a column. 
The valid variables in the order by clause must refer to the name of a column
The value of the parameter sort is_ the name of a column!

Any hint?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 5 2008
Added on Aug 7 2008
4 comments
1,632 views