【问题标题】:Get the named query string within JPA在 JPA 中获取命名的查询字符串
【发布时间】:2011-08-07 23:24:45
【问题描述】:

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

有没有其他方法可以解决这个问题来获取命名查询字符串,比如 Hibernate 暴露?类似于 JPA 中的getSession().getNamedQuery("namedQueryName");

谢谢, 索努。

【问题讨论】:

  • 什么样的“操纵目的”?我看不出一个令人信服的理由来外部化字符串然后对其进行操作,而不是仅仅将名称传递给createNamedQuery()。将字符串外部化以将 Java 代码与 JPQL 解耦不是重点吗?如果你试图解耦逻辑,对它执行字符串操作听起来更像是代码异味。

标签: java oracle jpa


【解决方案1】:

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

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

【讨论】:

  • 谢谢,正是我想要的。我也试图获得另一种方法。 Session session = ((Session) entityManager.getDelegate());字符串查询 = session.getNamedQuery('NamedQueryName');
  • 完美解决方案!谢谢!
【解决方案2】:

哦,你可以使用自省来获取命名查询注释,例如:

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

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多