JPA Native Query Example

By | | Updated : 2021-09-19 | Viewed : 409 times

JPA Native Query Example

In this tutorial, we understand the usage of @NamedNativeQuery annotation in JPA. @NamedNativeQuery is used for fetching the records underlying the database. Here native query of the required database will be passed as input to the @NamedNativeQuery.

Write @NamedNativeQuery in the entity

In this current example, we will fetch the records from the player table of MySQL DB. here we have the implementation below for @NamedNativeQuery.

Player entity for @NamedNativeQuery definition
@Table(name = "player")
                name = "Player-query",
                query = "SELECT player.* FROM PLAYER AS player WHERE player.ID = ?",
                resultClass = Player.class
public class Player implements Serializable {
	//properties and setters/getters

Here we used the @NamedNativeQuery for fetching the player tables records. Here the query contains the parameters too. We will pass inputs for the same later when we execute the @NamedNativeQuery.

Note: @NamedNativeQueries is used for creating multiple native queries. Please see the above example of how it is used.

Fetch the result of @NamedNativeQuery

We will use the method createNamedQuery() with the input of the name of @NamedNativeQuery. Notice the name of @NamedNativeQuery in the Player entity is Player-query. So the same string will be used in the createNamedQuery() method. for fetching the records using @NamedNativeQuery
public class MainClient {

    public static void main(String[] args) {
        System.out.println("main method @MainClient");

        EntityManager entityManager = JPAUtils.getEntityManagerFactory().createEntityManager();
        EntityTransaction transaction = null;
        try {

            transaction = entityManager.getTransaction();

            System.out.println("Using createNativeQuery method");
            String sql = "SELECT player.* FROM PLAYER AS player WHERE player.ID = ?";

            Query query = entityManager.createNativeQuery(sql, Player.class);
            query.setParameter(1, "1000010");
            Player player = (Player) query.getSingleResult();


            System.out.println("Using NamedNativeQuery annotation");
            Query query1 = entityManager.createNamedQuery("Player-query", Player.class);
            query1.setParameter(1, 1000011);
            Player player1 = (Player) query1.getSingleResult();


        } catch (Exception ex) {
            if (transaction != null) {
        } finally {

For the entire code of this @NamedNativeQuery usage example you can refer to the GitHub repo JPA-Native-Query-Example-App

Leave A Reply