JPA Native Query Example

By | | Updated : 2021-09-19 | Viewed : 55 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
@Getter
@Setter
@ToString
@Entity
@Table(name = "player")
@NamedNativeQueries({
        @NamedNativeQuery(
                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.

MainClient.java 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();
            transaction.begin();

            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(player.getFirstName());
            System.out.println(player.getLastName());

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

            transaction.commit();

        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }
}

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

Leave A Reply