Search code examples
javajpareflectionannotationsnamed-query

How to determine if an Entity has a NamedQuery


Again, posting and answering a question for the benefit of others based on a problem I had the other day. Hopefully this saves someone a bit of time. I was a little surprised this wasn't built into JPA's EntityManager.

How can I determine if an Entity has a NamedQuery annotation with a specific name?

I need to determine if an Entity has a particular @NamedQuery before I try executing it.


Solution

  • When annotations are nested, you can get the properties of the annotation to get it's children. In the case of @NamedQueries, it's .value().

    public boolean hasNamedQuery(Class<?> clazz, String nameOfQuery) {
        boolean foundQueryByName = false;
        NamedQueries namedQueries = clazz.getAnnotation(NamedQueries.class);
        if (namedQueries != null && namedQueries.value() != null) {
            NamedQuery[] values = namedQueries.value();
            for (int i = 0; i < values.length && !foundQueryByName; i++) {
                foundQueryByName |= (nameOfQuery.equals(values[i].name()));
            }
        }
        return foundQueryByName;
    }