Skip to lesson

Native SQL queries

The owner wants a sales report that ranks categories by revenue and shows each one's share of the total. JPQL has no window functions, and falling back to JDBC for every report would throw away what Spring Data gives.

@Query(nativeQuery = true) and @NativeQuery

A native query is plain SQL for your database, such as MySQL, written on a repository method and sent as written. Mark it with @NativeQuery or @Query(nativeQuery = true); values are still bound safely.

ShopLite's category report needs rank() over (...), which JPQL cannot express. In native SQL, table and column names are used directly.

Example 1 · src/main/java/com/shoplite/report/SalesReportRepository.java: a window-function report

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

CategorySales.javaJava
// src/main/java/com/shoplite/report/CategorySales.javapackage com.shoplite.report;
import java.math.BigDecimal;
/** One row of the category sales report. Getter names match the column aliases. */public interface CategorySales {
    String getCategory();
    BigDecimal getRevenue();
    Long getSalesRank();
    BigDecimal getSharePercent();}
// src/main/java/com/shoplite/report/SalesReportRepository.javapackage com.shoplite.report;
import java.util.List;
import org.springframework.data.jpa.repository.NativeQuery;import org.springframework.data.repository.Repository;
import com.shoplite.product.Product;
/** Read-only reports in MySQL SQL. Extends the bare Repository, so it has no save or delete methods. */public interface SalesReportRepository extends Repository<Product, Integer> {
    @NativeQuery("""            select c.name as category,                   sum(oi.quantity * oi.unit_price) as revenue,                   rank() over (order by sum(oi.quantity * oi.unit_price) desc) as salesRank,                   round(100 * sum(oi.quantity * oi.unit_price)                         / sum(sum(oi.quantity * oi.unit_price)) over (), 1) as sharePercent            from order_items oi            join orders o on o.order_id = oi.order_id            join products p on p.product_id = oi.product_id            join categories c on c.category_id = p.category_id            where o.status <> 'CANCELLED'            group by c.name            order by salesRank, c.name""")    List<CategorySales> categorySales();}
// src/main/java/com/shoplite/lab/NativeTour.java (profile "native")System.out.printf("%-12s %10s %5s %6s%n", "Category", "Revenue", "Rank", "Share");for (CategorySales row : reports.categorySales()) {    System.out.printf("%-12s %10s %5d %5s%%%n",            row.getCategory(), row.getRevenue(), row.getSalesRank(), row.getSharePercent());}
Sample output
--- categorySales()
Category        Revenue  Rank  Share
DEBUG org.hibernate.SQL : select c.name as category,
       sum(oi.quantity * oi.unit_price) as revenue,
       rank() over (order by sum(oi.quantity * oi.unit_price) desc) as salesRank,
       round(100 * sum(oi.quantity * oi.unit_price)
             / sum(sum(oi.quantity * oi.unit_price)) over (), 1) as sharePercent
from order_items oi
join orders o on o.order_id = oi.order_id
join products p on p.product_id = oi.product_id
join categories c on c.category_id = p.category_id
where o.status <> 'CANCELLED'
group by c.name
order by salesRank, c.name
Laptops       150970.00     1  49.4%
Mobiles       126397.00     2  41.4%
Accessories    13941.00     3   4.6%
Fashion         8594.00     4   2.8%
Books           5741.00     5   1.9%

What this code does

  • The SQL in the log is exactly the text in the annotation: Hibernate does not translate a native query, it only binds parameters and sends it.
  • rank() over (...) numbers the categories by revenue, and sum(sum(...)) over () is the total of all groups, so each row can show its share. Cancelled orders are left out. The shares are rounded separately, so they add up to 100.1.
  • CategorySales is an interface projection: Spring Data matches each column alias (salesRank) to a getter (getSalesRank). MySQL's rank() is a BIGINT, so the getter returns Long.

@NativeQuery needs Spring Data JPA 3.4 or later; @Query(value = "select ...", nativeQuery = true) works in every version. JPQL covers normal reads, but reports often need database features: window functions like rank() over (...), REGEXP, JSON functions or vendor hints. The category report ranks categories by revenue and shows each one's share of total sales in one statement.

A read-only report does not belong in ProductRepository. Here it lives in its own SalesReportRepository, which extends the bare Repository marker so it exposes no save or delete methods at all.

Mapping native results to entities or to interface projections

An interface projection is an interface whose getters receive the selected columns: each column alias is matched to a getter, so as salesRank fills getSalesRank().

Entities suit data you will change; a report only shows it. Compare a native query that returns entities with one that returns a projection.

Example 2 · Native results as entities and as an interface projection

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

StockAlert.javaJava
// src/main/java/com/shoplite/product/ProductRepository.java (two native methods)@NativeQuery("select * from products where sku regexp :pattern order by product_id")List<Product> findBySkuPattern(@Param("pattern") String pattern);
@Query(value = """        select p.sku as sku, p.name as name, c.name as categoryName        from products p        join categories c on c.category_id = p.category_id        where p.stock = 0        order by p.sku""", nativeQuery = true)List<StockAlert> findOutOfStock();
// src/main/java/com/shoplite/product/StockAlert.javapublic interface StockAlert {
    String getSku();
    String getName();
    String getCategoryName();}
// NativeTourproducts.findBySkuPattern("^(MOB|LAP)-").forEach(p -> System.out.println("  " + p.getSku() + " " + p.getName()));for (StockAlert alert : products.findOutOfStock()) {    System.out.println("  " + alert.getSku() + " | " + alert.getName() + " | " + alert.getCategoryName());}
Sample output
--- findBySkuPattern("^(MOB|LAP)-")
DEBUG org.hibernate.SQL : select * from products where sku regexp ? order by product_id
  MOB-RN13 Redmi Note 13 5G
  MOB-GM35 Samsung Galaxy M35
  MOB-IP15 iPhone 15 128GB
  LAP-IPS3 Lenovo IdeaPad Slim 3
  LAP-HPV15 HP Victus 15 Gaming
--- findOutOfStock()
DEBUG org.hibernate.SQL : select p.sku as sku, p.name as name, c.name as categoryName
from products p
join categories c on c.category_id = p.category_id
where p.stock = 0
order by p.sku
  ACC-M331 | Logitech M331 Silent Mouse | Accessories
  ACC-USBC1 | USB-C Cable 1m | Accessories

What this code does

  • regexp is MySQL-only, so JPQL cannot express it. With List<Product> as the return type, Hibernate maps each row of select * back to a full Product entity by column name.
  • @Query(value = ..., nativeQuery = true) and @NativeQuery(...) (Spring Data JPA 3.4+) mean the same thing; the second is shorter.
  • StockAlert gets only the three aliased columns. A missing alias, or one spelled differently from the getter, gives null for that getter.

List<Product> with select * (or every mapped column) gives managed entities, matched by column name. Use entities when you will change or reuse the objects; use projections for reports and lists that only show data. Projections can also return columns from several tables, such as a category name next to product fields.

What can go wrong: an entity result needs every mapped column, or Hibernate fails with a missing-column error. A projection getter whose alias is missing or misspelt silently returns null.

Name aliases in camelCase exactly like the getters. MySQL keeps the alias as you typed it.

Parameters are still bound safely; never build SQL by joining strings

SQL injection is input that changes a query's meaning because it was pasted into the SQL text, such as x' or '1'='1. Binding values as parameters prevents it.

A SKU search box receives x' or '1'='1. Compare a query built by joining strings with one that binds the value.

Example 3 · src/main/java/com/shoplite/lab/InjectionTour.java: joined strings vs a bound parameter

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
package com.shoplite.lab;
import java.util.List;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
import jakarta.persistence.EntityManager;
@Component@Profile("injection")class InjectionTour implements CommandLineRunner {
    private final EntityManager entityManager;    private final ProductRepository products;
    InjectionTour(EntityManager entityManager, ProductRepository products) {        this.entityManager = entityManager;        this.products = products;    }
    @Override    public void run(String... args) {        String typed = "x' or '1'='1";          // what an attacker types into the SKU search box
        System.out.println("--- WRONG: SQL built by joining strings");        String sql = "select * from products where sku = '" + typed + "'";        List<?> leaked = entityManager.createNativeQuery(sql, Product.class).getResultList();        System.out.println("rows returned: " + leaked.size());
        System.out.println("--- RIGHT: a bound parameter");        List<Product> safe = products.findBySkuNative(typed);        System.out.println("rows returned: " + safe.size());    }}
// ProductRepository@NativeQuery("select * from products where sku = :sku")List<Product> findBySkuNative(@Param("sku") String sku);
Sample output
$ mvn spring-boot:run -Dspring-boot.run.profiles=injection -Dspring-boot.run.arguments=--logging.level.org.hibernate.orm.jdbc.bind=TRACE
...
--- WRONG: SQL built by joining strings
DEBUG org.hibernate.SQL : select * from products where sku = 'x' or '1'='1'
rows returned: 15
--- RIGHT: a bound parameter
DEBUG org.hibernate.SQL : select * from products where sku = ?
TRACE org.hibernate.orm.jdbc.bind : binding parameter (1:VARCHAR) <- [x' or '1'='1]
rows returned: 0

What this code does

  • In the wrong version the quote in the input closes the SQL string, and or '1'='1' is always true: every product comes back. The same trick on a customers table would leak every e-mail and phone number.
  • In the right version the SQL text never changes. The bind log shows the whole input sent as one value, and no SKU equals that text, so 0 rows.
  • logging.level.org.hibernate.orm.jdbc.bind=TRACE prints bound values; keep it for local debugging only, because it also prints personal data.

Bound parameters (:sku, ?1) work in native queries exactly as in JPQL: the SQL text is fixed and values travel separately to MySQL, as Section 13 showed with JDBC. The danger comes back the moment someone builds SQL with + or String.format, for example with EntityManager.createNativeQuery to add an optional filter quickly. It works in testing and leaks data in production.

One honest limit: parameters can only stand for values, not for table names, column names or asc/desc. When sorting is user-controlled, map the user's choice through an allow-list ("price" becomes p.price) and never paste the raw text.

Find the bug

Find the injection

Each snippet takes text from a user. Tap the line that opens the door to SQL injection.

A SKU search built with EntityManager.

Round 1 of 3

Trade-offs: no startup check, tied to MySQL and to column names

A typo in native SQL does not stop the app. Break one column name on purpose and see when the error appears.

Example 4 · A typo in native SQL: the app starts, the call fails

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
// ProductRepository: "prise" instead of "price"@NativeQuery("select p.sku as sku, p.name as name, p.prise as price from products p where p.stock = 0")List<StockAlert> findCheapBroken();
// RepositoryCheck, after the countSystem.out.println("Calling findCheapBroken()");products.findCheapBroken();
Sample output
DEBUG org.hibernate.SQL : select count(*) from products p1_0
Products in table: 15
Calling findCheapBroken()
DEBUG org.hibernate.SQL : select p.sku as sku, p.name as name, p.prise as price from products p where p.stock = 0
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1054, SQLState: 42S22
WARN  org.hibernate.orm.jdbc.error : Unknown column 'p.prise' in 'field list'
ERROR o.s.boot.SpringApplication : Application run failed
org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [Unknown column 'p.prise' in 'field list'] [select p.sku as sku, p.name as name, p.prise as price from products p where p.stock = 0]; SQL [select p.sku as sku, p.name as name, p.prise as price from products p where p.stock = 0]
Caused by: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [Unknown column 'p.prise' in 'field list'] [select p.sku as sku, p.name as name, p.prise as price from products p where p.stock = 0]
	... 33 common frames omitted
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'p.prise' in 'field list'
	... 69 common frames omitted

What this code does

  • The application started and the repository was created without complaint: nobody checks native SQL at startup. The error came from MySQL (error 1054) only when the method ran.
  • In a real app this would be a 500 on the first request that reaches the report, possibly days after the deploy. A test that calls every native query is the only early warning.

The cost of native SQL is everything JPQL was doing for you. Spring Data cannot parse MySQL SQL, so a typo is found only when the query runs. The query is tied to MySQL syntax, so a move to PostgreSQL means rewriting it. It is tied to column names, so renaming a column in a Flyway migration breaks it without any compiler or startup warning.

The rule is simple: default to derived methods and JPQL, and use native SQL when a database feature really pays for itself, such as reports with window functions, full-text search or a carefully tuned query. Keep those queries few, in clearly named report repositories, and cover each with a test that runs it against MySQL. In short:

  • JPQL: checked at startup, portable, uses entity names
  • Native: MySQL features, checked only when called, uses table and column names
  • Both: bind every value; never concatenate input

Next step

Check your understanding

12 quick questions