[en] Get NamedQuery as string in Eclipselink

It’s nice to have all the queries in one place and @NamedQuery give you just that. But what if you need to have parametrized ORDER BY or stuff like that — NamedQueries are static and cannot be modified and ORDER can’t use a parameter.

There is no simple way to customize the NamedQuery, too. You can use setMaxResults but not „setOrder”.

My solution is to read @NamedQuery annotation’s „query” parameter and construct the query myself, adding necessary ORDER BY clause.

The code is (Eclipselink-specific):

import javax.persistence.NamedQuery;
import javax.persistence.Query;
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.queries.DatabaseQuery;
// (...)
public String getNamedQueryString(String namedQuery) {
    Query tmpQuery = entityManager.createNamedQuery(namedQuery);
    DatabaseQuery databaseQuery = ((EJBQueryImpl) tmpQuery).getDatabaseQuery();
    Class resultClass = databaseQuery.getReferenceClass();

    NamedQuery annotation = (NamedQuery) resultClass.getAnnotation(NamedQuery.class);

    // it's possible there's NamedQueries instead of single NamedQuery annotation
    if (annotation == null) {
        NamedQueries annotations = (NamedQueries) resultClass.getAnnotation(NamedQueries.class);
        for (NamedQuery nq : annotations.value()) {
            if (namedQuery.equals(nq.name())) {
                annotation = nq;

    return annotation.query();
// (...)