2011-04-18 37 views
4

我想在orm.xml文件中为JPA的所有命名查询进行外部化。我想在我的Java程序中获取命名的查询字符串,以便进行某些操作,但JPA似乎没有公开任何以字符串形式返回命名查询的方法。我所能做的就是createNamedQuery,它带有指定查询的名称。获取JPA中指定的查询字符串

是否有任何其他解决此问题的方法来获取像Hibernate这样的命名查询字符串?类似于JPA中的getSession().getNamedQuery("namedQueryName");

谢谢, Sonu。

+0

什么样的“操作目的”?我看不到一个令人信服的理由来外化字符串,然后操作它,而不是将名称传递给'createNamedQuery()'。将字符串外部化是不是将Java代码与JPQL分离开来的关键点?如果你想解耦逻辑,对它进行字符串操作听起来就像是一种代码异味。 – 2011-04-18 15:16:10

回答

11

如果你确实需要,可以随时通过JPA访问特定供应商类(含unwrap()在JPA 2.0,或者与以前的版本向下转换):

String s = em.createNamedQuery("...") 
    .unwrap(org.hibernate.Query.class) 
    .getQueryString(); 
+0

谢谢,正是我在找的东西。我也试图找到一种替代方法。 Session session = ((Session) entityManager.getDelegate()); String query = session.getNamedQuery('NamedQueryName'); Prashanth 2011-04-18 16:22:28

+0

完美的解决方案!谢谢! – 2015-04-24 12:23:15

4

哦,你可以用内省得到命名查询注释如:

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