The moose likes Object Relational Mapping and the fly likes Dynamically setting sort direction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Dynamically setting sort direction" Watch "Dynamically setting sort direction" New topic

Dynamically setting sort direction

Eugene Williams

Joined: Jan 31, 2010
Posts: 20
I'm working on an application where I'd like to dynamically determine whether the sorting returned during an HQL query is in descending or ascending order.
When trying to do this using a named query, I get errors during deployment. Here's an example of the code from the domain object:

In the DAO (using Spring), I call the query using a statement (eg.):

This doesn't work. I've even tried adding a case statement in the domain object:

Is there a way to dynamically set whether the results are in ascending or descending order or will I have to create two separate named queries for this (i.e. listcontacts_bytype_desc & listcontacts_bytype_asc)? (Or do something much simpler that I'm not thinking of).

Eugene Williams

Joined: Jan 31, 2010
Posts: 20
It appears that this may not be possible (based upon responses I've seen in other forums)

I have come across something else, however, after further testing, it appears that I'm also not getting the "order" parameter set during my query either. Is it not possible to set the "order" parameter dynamically using ?

James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
Correct, parameters are for executing the same query with different values.

Order by and asc/desc are not parameters they are part of the query syntax, you cannot use parameters for this.

You will need to create your query dynamically. Either by building your own JPQL based on your arguments, or using the JPA 2.0 Criteria API which is for building dynamic queries.

If you want static queries, then you would need multiple different named queries for each type of query.

TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Eugene Williams

Joined: Jan 31, 2010
Posts: 20
Thanks for the guidance.
I agree. Here's the link: http://aspose.com/file-tools
subject: Dynamically setting sort direction
Similar Threads
Only one named query allowed???
Named queries and EJBQL
Pagination with Sorting
sorting by and using charAt
Can't reach NamedQuery