DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Grounding AI Agents in Governed Data
  • Engineering Self-Healing SQL Pipelines With LLMs: Validation, Guardrails, and Safe Recovery

Trending

  • New York City Taxi Trips: Putting Neo4j and DuckDB to Work
  • When a Coding Agent Fixes the Test Instead of the Bug
  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Native Queries: How to Call Native SQL Queries With JPA

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.

By 
Thorben Janssen
·
Apr. 18, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
54.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The 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.

Database sql

Published at DZone with permission of Thorben Janssen. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Grounding AI Agents in Governed Data
  • Engineering Self-Healing SQL Pipelines With LLMs: Validation, Guardrails, and Safe Recovery

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook