[en] Get NamedQuery as string in Eclipselink

It’s nice to have all the queries in one pla­ce and @NamedQuery give you just that. But what if you need to have para­me­tri­zed ORDER BY or stuff like that — Name­dQu­eries are sta­tic and can­not be modi­fied and ORDER can’t use a parameter.

The­re is no sim­ple way to custo­mi­ze the Name­dQu­ery, too. You can use set­Ma­xRe­sults but not „setOr­der”.

My solu­tion is to read @NamedQuery anno­ta­tio­n’s „query” para­me­ter and con­struct the query myself, adding neces­sa­ry ORDER BY clause.

The code is (Eclip­se­link-spe­ci­fic):

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;
                break;
            }
        }
    }

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