[英]Get the named query string within JPA
I am trying to externalize all named queries for JPA in an orm.xml file. 我试图在orm.xml文件中外部化JPA的所有命名查询。 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.
我想在我的Java程序中获取命名查询字符串用于某些操作目的,但JPA似乎没有公开任何将命名查询作为字符串返回的方法。 All I can do is
createNamedQuery
with the name of the named query. 我所能做的就是使用命名查询的名称
createNamedQuery
。
Is there any other way around this problem to get the named query string like Hibernate exposes ? 有没有其他方法来解决这个问题,以获得像Hibernate公开的命名查询字符串? Similar to
getSession().getNamedQuery("namedQueryName");
与
getSession().getNamedQuery("namedQueryName");
类似getSession().getNamedQuery("namedQueryName");
in JPA? 在JPA?
Thanks, Sonu. 谢谢,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): 如果您确实需要,您可以始终通过JPA(在JPA 2.0中使用
unwrap()
或在先前版本中使用向下转换unwrap()
访问特定于提供程序的类:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.