oracle 获取 JPA 中的命名查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5704917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the named query string within JPA
提问by Prashanth
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.
我正在尝试在 orm.xml 文件中外部化 JPA 的所有命名查询。我想在我的 Java 程序中获取命名查询字符串以用于某些操作目的,但 JPA 似乎没有公开任何将命名查询作为字符串返回的方法。我所能做的就是createNamedQuery
使用命名查询的名称。
Is there any other way around this problem to get the named query string like Hibernate exposes ? Similar to getSession().getNamedQuery("namedQueryName");
in JPA?
有没有其他方法可以解决这个问题来获取像 Hibernate 公开这样的命名查询字符串?类似于getSession().getNamedQuery("namedQueryName");
在 JPA 中?
Thanks, Sonu.
谢谢,索努。
回答by axtavt
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):
如果您确实需要,您始终可以通过 JPA 访问特定unwrap()
于提供程序的类(在 JPA 2.0 中,或在以前的版本中向下转换):
String s = em.createNamedQuery("...")
.unwrap(org.hibernate.Query.class)
.getQueryString();
回答by alessandro
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;
}