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).
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 ?
Joined: Oct 01, 2007
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.