Native Queries: How to Call Native SQL Queries With JPA
JPA has its own query language and supports native SQL. You can create queries in a very similar way as JPQL queries and they can even return managed entities.
Join the DZone community and get the full member experience.
Join For FreeThe Java Persistence Query Language (JPQL) is the most common way to query data from a database with JPA. But it supports only a small subset of the SQL standard and it also provides no support for database specific features.
So what should you do if you need to use a database-specific query feature or your DBA gives you a highly optimized query that cannot be transformed into JPQL? Just ignore it and do all the work in the Java code?
Of course not! JPA has its own query language but it also supports native SQL. You can create these queries in a very similar way as JPQL queries and they can even return managed entities if you want.
Create Dynamic Native Queries
Creating a dynamic native query is quite simple. The EntityManager
interface provides a method called createNativeQuery
for it. This method returns an implementation of the Query interface which is the same as if you call the createQuery
method to create a JPQL query.
The following code snippet shows a simple example in which I used a native query to select the first and last names from the author table. I know that there is no need to do this with a native SQL query. I could use a standard JPQL query for this, but I want to focus on the JPA part and not bother you with some crazy SQL stuff.
The persistence provider does not parse the SQL statement, so you can use any SQL statement that is supported by your database. In one of my recent projects, for example, I used it to query PostgreSQL specific jsonb
columns with Hibernate and mapped the query results to POJOs and entities.
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
for (Object[] a : authors) {
System.out.println("Author "
+ a[0]
+ " "
+ a[1]);
}
As you can see, the created query can be used in the same way as any JPQL query. I didn’t provide any mapping information for the result, so EntityManager
returns a List of Object[]
, which needs to be handled afterward. Instead of mapping the result yourself, you can also provide additional mapping information and let the EntityManager
do the mapping for you. I get into more details about that in the result handling section at the end of this post.
Published at DZone with permission of Thorben Janssen, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments