Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the named query string within JPA

Tags:

java

oracle

jpa

I am trying to externalize all named queries for JPA in an orm.xml file. I would like to get the named query string in my Java program for some manipulation purposes but JPA doesnt seem to expose any method that returns the named query as a string. All I can do is createNamedQuery with the name of the named query.

Is there any other way around this problem to get the named query string like Hibernate exposes ? Similar to getSession().getNamedQuery("namedQueryName"); in JPA?

Thanks, Sonu.

like image 747
Prashanth Avatar asked Dec 02 '22 02:12

Prashanth


2 Answers

If you actually need, you can always access provider-specific classes via JPA (with unwrap() in JPA 2.0, or with downcasting in previous versions):

String s = em.createNamedQuery("...")
    .unwrap(org.hibernate.Query.class)
    .getQueryString();
like image 69
axtavt Avatar answered Dec 04 '22 07:12

axtavt


oh well you can use introspection to get named queries annotations like:

String getNamedQueryCode(Class<? extends Object> clazz, String namedQueryKey) {
    NamedQueries namedQueriesAnnotation = clazz.getAnnotation(NamedQueries.class);
    NamedQuery[] namedQueryAnnotations = namedQueriesAnnotation.value();

    String code = null;
    for (NamedQuery namedQuery : namedQueryAnnotations) {
        if (namedQuery.name().equals(namedQueryKey)) {
            code = namedQuery.query();
            break;
        }
    }

    if (code == null) {
        if (clazz.getSuperclass().getAnnotation(MappedSuperclass.class) != null) {
            code = getNamedQueryCode(clazz.getSuperclass(), namedQueryKey);
        }
    }

    //if not found
    return code;
}
like image 35
alessandro Avatar answered Dec 04 '22 08:12

alessandro