Native Query – How to call native SQL query with JPA

Native Query – How to call native SQL query with JPA

The Java Persistence Query Language (JPQL) is that most common using to query data from a database with JPA. It supports a small subset of the SQL queries. JPA has its own query language (i.e. JPQL) but it supports native SQL queries also.  You can create these queries in a very similar way like JPQL queries and they can even return either object or entities.

Native queries creation or how to create native queries:

To creating a native query is quite simple with JPA. The EntityManager interface provides a method called createNativeQuery . The createNativeQuery() method returns an implementation of the Query interface which is the same as the createQuery() method to create a JPQL query.

Define the attributes to select statement:

Generally many developers use the JPQL to fetch the results/entities. But that’s not the only way you can use. You can define a list of entity attributes which you want to select values.
Example:
List<Object> empNames = entityManager.createQuery(“SELECT e FROMEMPLOYEE e”)
OR
List<Employee> empNames = entityManager.createQuery(“SELECT e FROM EMPLOYEE e”)

(To be continued...)

Comments