Enumerating @NamedQuery within @NamedQueries

David
2 min readJun 26, 2021
A black and white image of music with a glass next to it.
Photo by Xavier von Erlach on Unsplash

If you’re a Java developer using JPA, chances are that you’ve declared one or more @NamedQuery objects on your entities.

To declare a @NamedQuery on a class, the class must simply be annotated with the name of the query and its JPQL, such as:

@Entity
@NamedQuery(name = "findAllProjects",
query = "select p from Project p order by p.id")
public class Project

If however, we wish to declare multiple @NamedQuery annotations, we annotate the class with a @NamedQueries annotation which then contains a collection of @NamedQuery annotations as follows:

@Entity
@NamedQueries({
@NamedQuery(name = "findAllProjects",
query = "select p from Project p order by p.id"),
@NamedQuery(name = "findById",
query = "select p from Project p where p.id=:id")
})
public class Project

Enumerating the @NamedQuery annotations

Once you’ve created an entity with multiple @NamedQuery annotations, how can you check what annotations are present on the class?

Fortunately using reflection, its a fairly simple matter to enumerate the annotations on the class and find the details about them as shown in the following code.

NamedQueries annotation = Project.class.getAnnotation(
NamedQueries.class
);
for (Annotation annot : annotation.value()) {
System.out.println(annot.toString());
for (Method method : annot.annotationType().getDeclaredMethods()) {
if (method.getName().equalsIgnoreCase("name") ||
method.getName().equalsIgnoreCase("query")) {
try {
String result = method.getName() +
" : " +
method.invoke(annot, null).toString();
System.out.println(result);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// Oops - something has gone wrong.
break;
}
}
}
}

Running the above code produces the following output:

@javax.persistence.NamedQuery(lockMode=NONE, hints=[], name=findAllProjects, query=select p from Project p order by p.id)
name : findAllProjects
query : select p from Project p order by p.id

@javax.persistence.NamedQuery(lockMode=NONE, hints=[], name=findById, query=select p from Project p where p.id=:id)
name : findById
query : select p from Project p where p.id=:id

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

David
David

Written by David

Full Stack Web Developer, Lover of the Cloud

No responses yet

Write a response