I have a named query as below;
@NamedQuery(name = "MyEntityClass.findSomething", query = "SELECT item FROM MyTable mytbl")
Now I want to append dynamic sort clause to this query (based on UI parameters)
Can I get an example using JPQL for doing the same (like how to set a dynamic ORDER BY in the Entity class)
I have already tried using CriteriaQuery, but was looking for a JPQL implementation now.
@NameQuery
JPQL
toSQL
at deployment time.@NameQuery
annotation at runtime.Reflection API
, to change the annotation value at runtime. I think It is not solution, also it is not you wanted .em.createQuery()
JPQL
toSQL
every time it is invoked.NamedQueries are by definition NOT dynamic, it is not correct to change them programmatically.
So the way to go is to create a JPQL query (but not a named query) like this:
On the other hand, if you REALLY want to use the named query, you could do that the following way:
As of JPA 2.1 it is possible to define named queries programmatically.
This can be achieved using
entityManagerFactory.addNamedQuery(String name, Query)
.Example:
Reference here
This can be useful, for instance, if you have the orderby field defined as a application parameter. So, when the application starts up or on the first run of the query, you could define the NamedQuery with the defined OrderBy field.
On the other side, if your OrderBy can be changed anytime (or changes a lot), then you need dynamic queries instead of NamedQuery (static). It would not worth to (re)create a NamedQuery every time (by performance).