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.
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();
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With