JPA 中所有命名查询的列表

2024-05-20

我想获取应用程序中所有 NamedQueries 的列表,并且我还想在运行时一般调用它们。是否有一个选项可以获取列表以及某种元数据(一般来说是某种反射)?

另一个线程为 NHibernate 提供了某种解决方案...即使使用 Hibernate 作为实现,也无法在 JPA 中找到类似的解决方案。

提前谢谢 副司令


我不认为有任何东西可以一步完成这一内置操作。但是您可以使用 JPA2 中的元模型以及一些简单的反射来完成此操作:

private static Set<NamedQuery> findAllNamedQueries(EntityManagerFactory emf) {
    Set<NamedQuery> allNamedQueries = new HashSet<NamedQuery>();

    Set<ManagedType<?>> managedTypes = emf.getMetamodel().getManagedTypes();
    for (ManagedType<?> managedType: managedTypes) {
        if (managedType instanceof IdentifiableType) {
            @SuppressWarnings("rawtypes")
            Class<? extends ManagedType> identifiableTypeClass = managedType.getClass();

            NamedQueries namedQueries = identifiableTypeClass.getAnnotation(NamedQueries.class);
            if (namedQueries != null) {
                allNamedQueries.addAll(Arrays.asList(namedQueries.value()));
            }

            NamedQuery namedQuery = identifiableTypeClass.getAnnotation(NamedQuery.class);
            if (namedQuery != null) {
                allNamedQueries.add(namedQuery);
            }
        }
    }
    return allNamedQueries;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JPA 中所有命名查询的列表 的相关文章

随机推荐