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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • DuckDB for Python Developers
  • Custom Model Context Protocol (MCP) for NL2SQL: A Rigorous Evaluation Framework on Oracle Database
  • Chat with Your Oracle Database: SQLcl MCP + GitHub Copilot
  • Push Filters Down, Not Up: The Data Layer Design Principle Most Developers Learn Too Late

Trending

  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  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 user avatar
Thorben Janssen
·
Apr. 18, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
54.7K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • DuckDB for Python Developers
  • Custom Model Context Protocol (MCP) for NL2SQL: A Rigorous Evaluation Framework on Oracle Database
  • Chat with Your Oracle Database: SQLcl MCP + GitHub Copilot
  • Push Filters Down, Not Up: The Data Layer Design Principle Most Developers Learn Too Late

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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