获取JPA中的命名查询字符串

时间:2011-04-18 15:05:38

标签: java oracle jpa

我正在尝试在orm.xml文件中外部化JPA的所有命名查询。我想在我的Java程序中获取命名查询字符串用于某些操作目的,但JPA似乎没有公开任何将命名查询作为字符串返回的方法。我只能使用命名查询的名称createNamedQuery

有没有其他方法来解决这个问题,以获得像Hibernate公开的命名查询字符串?与JPA中的getSession().getNamedQuery("namedQueryName");类似吗?

谢谢, SONU。

2 个答案:

答案 0 :(得分:13)

如果您确实需要,您可以随时通过JPA(在JPA 2.0中使用unwrap()或在先前版本中使用向下转换)访问特定于提供者的类:

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

答案 1 :(得分: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;
}