JPA Native Query Example
By AmarSivas | | Updated : 2021-09-19 | Viewed : 229 times

In this tutorial, we understand the usage of
Table of Contents:
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
@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
Fetch the result of @NamedNativeQuery
We will use the method
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