Using Named Queries in JPA

I hope you might have gone through the JPA Overview in one of our previous articles. We will move move ahead on how to use Named Queries in JPA.

A named query is predefined query structure in the entity class, which improves code organisation in a way separating it from the Java code. It allows using query parameters that can be efficiently used in forming the actual query dynamically.

Named Queries using Annotations

Basically, we have two annotations that we can use to specify the Named Query: @NamedQuery and @NamedQueries


@NamedQuery and @NamedQueries Annotations

You must have an Entity class created something like:

If there is only one named query you want to specify, you can just @NamedQuery annotation. But if you need multiple Named Queries, you need to wrap them within the @NamedQueries annotation as shown below:

Getting the EntityManager object

Now you need to get the EntityManager object as:

Executing Named Queries

In order to find the Named Queries, JPA requires listing the entity classes in persistence unit definition in the persistence.xml file as –

Named Queries with XML mapping

With XML mapping instead of annotation, below are the files that will be different from what we have done above with annotations –

Firstly the Employee entity will change to simple POJO without any annotations, like –

Create Employee mapping XML file named as EmployeeMapping.xml and put it into the META-INF sub-directory.

There goes a slight change in the persistence.xml file as well. We need to specify the <mapping-file> element value as highlighted in the below code snippet –

Make sure to put persistence.xml file as well into the META-INF sub-directory.

For any clarification/queries on this, kindly post them as comments so that we can add the improvement in our future articles.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.