Spring Data JPA Native Query Examples

Code Java
18 Feb 202216:39

Summary

TLDRThis video tutorial, presented by Nam Hamming from Code Server Net, provides an in-depth guide on using native SQL queries with Spring Data JPA. The video covers key concepts such as what native queries are, when to use them, and how to implement select and update operations using native queries. It explains the difference between JPQL and native queries, demonstrates how to write native SQL queries for MySQL databases, and showcases testing methods for querying and updating data. Additionally, the tutorial covers pagination and query optimization with native SQL in a Spring Boot application.

Takeaways

  • 🔍 Native queries are SQL statements specific to a database, used when JPQL doesn't work or doesn't support the required query syntax.
  • 💻 Spring Data JPA supports native queries through the `@Query` annotation, where you must specify `nativeQuery=true` to indicate it's an SQL statement.
  • 📊 Native queries use table names directly from the database, not entity names, since the SQL statement targets the database structure.
  • 🛠 The example provided demonstrates a native query to select products with prices less than a given value using MySQL.
  • 🔄 Pagination can be implemented with native queries by passing a `Pageable` object and appending SQL `LIMIT` clauses for result sets.
  • 📋 For update operations, a native query must be annotated with both `@Query` and `@Modifying`, which allows modification of database records like updating prices.
  • 🧪 Unit testing for native queries can be done using simple methods that call the repository and verify returned data or modifications.
  • 📈 A count query can be specified in a native query annotation for efficient pagination, though Spring Data JPA handles this by default.
  • ⚠️ When using `@Modifying` with update queries, ensure correct SQL syntax is followed to avoid errors during execution.
  • ✅ Native queries are useful when database-specific features or SQL syntax need to be used, especially for more complex operations like full-text search.

Q & A

  • What is a native query in Spring Data JPA?

    -A native query is an SQL statement specific to a particular database. It differs from JPQL (Java Persistence Query Language), which Spring Data JPA uses by default.

  • When should a native query be used instead of JPQL in Spring Data JPA?

    -A native query should be used when JPQL does not support the required query syntax. For example, if a database-specific SQL feature or syntax is needed, native queries are used.

  • How do you declare a native query in Spring Data JPA?

    -To declare a native query, use the `@Query` annotation with the `nativeQuery=true` attribute. The SQL statement should be passed as the value of the annotation.

  • What is the key difference between a native query and JPQL?

    -In native queries, table names from the database are used, while in JPQL, entity names are used. This is because native queries directly use SQL syntax.

  • How do you pass parameters in a native query?

    -You can pass parameters using named parameters in the query, such as `:minPrice`, and provide the value of the parameter when calling the method.

  • What are the steps to write a native query for selecting products with a price less than a specified value?

    -First, declare a method in the repository interface, annotate it with `@Query`, and write the SQL statement using the table name. Then, use the `nativeQuery=true` attribute and pass the price parameter.

  • How do you handle pagination in a native query?

    -To implement pagination in a native query, you can pass a `Pageable` object as a parameter. This allows Spring Data JPA to append the appropriate SQL syntax for pagination (such as `LIMIT` in MySQL).

  • What additional annotation is needed for executing a native update query?

    -In addition to `@Query`, the `@Modifying` annotation is required for native update queries in Spring Data JPA.

  • How do you execute an update query to modify product prices?

    -You declare a method with an `@Query` annotation, specify the SQL update statement, and use `@Modifying`. Then, the method is called, passing the new price value.

  • What happens if you don't use the `@Modifying` annotation for an update query?

    -If the `@Modifying` annotation is not used, Spring Data JPA will throw an error because it expects a select query but finds an update query instead.

Outlines

00:00

👋 Introduction to Native Queries with Spring Data JPA

In this opening segment, the presenter introduces the video, which focuses on using native queries with Spring Data JPA. It explains what a native query is, distinguishing it from JPQL (Java Persistence Query Language) by its specificity to certain databases like MySQL. The video intends to teach when and how to use native queries, especially in scenarios where JPQL falls short. The presenter also sets the agenda for the video, promising examples of select and update native queries, and usage of native queries for pagination.

05:03

🛠️ Example of Writing a Select Native Query

Here, the presenter walks through coding a native query for selecting products from a MySQL database. The example uses a Spring Boot project with a 'Product' entity mapped to a database table. A native SQL query is demonstrated, selecting products priced less than $1000 using a custom method in a repository interface. The method is annotated with `@Query`, and the SQL uses the table name rather than the entity name. After writing the query, the presenter runs a test to confirm it successfully returns only products under the specified price.

10:06

✅ Testing the Select Native Query with Max Price

This section focuses on testing the native query created in the previous paragraph. The presenter writes and runs a test case where the maximum price is set to 1000 USD, retrieving products that fall under this price range. The test confirms the correct execution of the query, showing the products below $1000 and excluding those above. The presenter highlights the importance of using native queries for database-specific functionality, such as MySQL's syntax, which is not supported by JPQL.

15:08

🔍 Using Pagination with Native Queries

This paragraph introduces pagination with native queries. The presenter explains how to implement pagination using the `Pageable` object in Spring Data JPA, creating requests that define the page number and size. They demonstrate how to retrieve the first set of products from the query and change parameters to display products from subsequent pages. The paragraph also covers using `@Query` with pagination and the `countQuery` to handle large datasets efficiently. The tests confirm that pagination works by showing a different set of results per page.

📝 Implementing Native Update Queries

This segment demonstrates how to write a native update query. The presenter codes a query to increase the price of all products in the database by a certain amount. The query is annotated with `@Modifying` since it involves modifying data. After coding, a unit test is written to confirm the successful execution of the update, showing that all product prices are updated in the database. The example highlights the difference between update queries and select queries, emphasizing the need for additional annotations.

📈 Conclusion: Mastering Native Queries with Spring Data JPA

The final segment recaps the key points of the video. It reviews what native queries are, when they should be used, and the benefits they offer, especially for database-specific features that JPQL doesn’t support. The presenter highlights the examples covered, including the select query, update query, and pagination. The video ends with a call to action for viewers to subscribe, like, and share the content.

Mindmap

Keywords

💡Native Query

A native query refers to an SQL statement that is specific to a particular database. In this video, it is contrasted with JPQL, the default query language in Spring Data JPA. Native queries are used when JPQL cannot handle specific database syntax, as seen in the example where a native query is written for MySQL to select products priced under 1000 USD.

💡JPQL (Java Persistence Query Language)

JPQL is a query language used in JPA (Java Persistence API) for accessing and manipulating data in a relational database. It is the default query language in Spring Data JPA. The video explains that while JPQL works in most cases, native queries are used when JPQL does not support a specific database syntax.

💡Spring Data JPA

Spring Data JPA is a part of the Spring Framework that provides an abstraction over JPA, making it easier to interact with relational databases. The video demonstrates how to use Spring Data JPA for native queries, showcasing examples like selecting products with specific conditions using custom native queries.

💡Repository Interface

A repository interface in Spring Data JPA is used to define methods for database operations. The video shows a repository interface extending JpaRepository, which allows custom queries, including native queries, to be written for selecting and updating data in a database.

💡Annotation

Annotations in Spring Data JPA are used to define the behavior of certain methods or entities. The video explains the use of the @Query annotation to define a native query, and the @Modifying annotation to handle update operations in the database.

💡Pagination

Pagination refers to dividing large sets of data into smaller pages for efficient handling and display. In the video, pagination is demonstrated using a Pageable object in a native query to limit the number of products retrieved from the database, such as showing only five items per page.

💡Entity

An entity is a class in JPA that maps to a database table. In the video, the 'Product' entity class is discussed, showing how it maps to the 'products' table in a MySQL database. The native query uses the table name in the database instead of the entity name.

💡Update Query

An update query is used to modify existing data in a database. The video demonstrates writing a native update query in Spring Data JPA to increase the price of all products by a specific amount. The @Modifying annotation is necessary for this type of operation.

💡SQL Statement

An SQL statement is a query used to interact with a database, written in SQL (Structured Query Language). The video illustrates the use of SQL statements within native queries in Spring Data JPA, showing how SQL syntax differs from JPQL, particularly when selecting or updating records.

💡Product Table

The product table refers to the table in the MySQL database that stores product information, such as price. The video uses this table in examples of native queries, showing how to select products based on price conditions and how to update product prices using native SQL.

Highlights

Introduction to native queries in Spring Data JPA, explaining when and why to use them.

Explanation that a native query is an SQL statement specific to a particular database, like MySQL, and differs from JPQL.

Native queries should be used when JPQL does not support a specific query syntax, necessitating the use of SQL.

Demonstrating how to code a native query to select products with a price less than a specified value in MySQL.

Important distinction that in native queries, table names from the database must be used, not entity names.

Explanation of how to write a custom native query using the @Query annotation in Spring Data JPA.

Showcasing how to test native queries with Spring Data JPA using JUnit, including the example of selecting products priced below $1000.

Demonstrating how pagination can be implemented with native queries, using the Pageable object in Spring Data JPA.

Explaining the use of named parameters in native queries and how they are substituted with actual values at runtime.

Highlighting the process of testing pagination with native queries, showing products on different pages.

Explanation of how to use count queries with native SQL for pagination in Spring Data JPA.

Walkthrough of creating and executing a native update query to increase product prices in the database.

Explanation of using the @Modifying annotation in Spring Data JPA when executing update or delete native queries.

Common pitfalls discussed, such as the need for the @Modifying annotation when running an update query.

Demonstration of successfully updating product prices using a native query, including checking the database for updated records.

Transcripts

play00:01

hi welcome to the video spring data jpi

play00:03

native query examples with me nam

play00:06

hamming from code server net

play00:08

in this video you will learn what is

play00:10

native query when using native query

play00:13

and how to use native queries with

play00:16

spring data api i'll show you some core

play00:18

examples about select native query

play00:21

update native query and how to use

play00:23

imagination with native query

play00:26

so what is native query you know a

play00:29

native query is the sql statement that

play00:31

is specific to a particular database

play00:34

for example mysql

play00:36

and a native query syntax default

play00:38

slightly from jpql or java persistence

play00:41

query language which is used by spring

play00:44

data jba by default

play00:47

and generally we should use native query

play00:50

when jpql does not work in other words

play00:53

the query is syntax not supported by

play00:55

jpql then we need to use native query

play01:03

now i'd like to show you how to code a

play01:06

native query for select operation

play01:09

okay you see this here springboard

play01:11

project you can see

play01:13

i'm using

play01:16

subbrain data jpi

play01:18

and

play01:19

mysql

play01:20

jdbc driver

play01:23

and in this project i have the product

play01:26

entity class that maps to the products

play01:29

table in the database

play01:32

and you can see in the database my sql

play01:36

i have the data in the product table

play01:39

like this you see

play01:41

okay and you see a

play01:44

standard

play01:46

repository interface

play01:49

following

play01:50

jpi you see

play01:52

it extends the jpa or repository

play01:55

interface

play01:58

and also i have a retest class for

play02:01

testing the product or repository

play02:04

interface you see

play02:06

now i want to

play02:08

write a native query that selects only

play02:11

products

play02:13

with price

play02:15

less than 1000 usd

play02:18

to do so i update the product repository

play02:22

interface here

play02:24

i

play02:25

declare new method public list

play02:29

list collection

play02:31

list of product

play02:33

read

play02:34

products

play02:39

with

play02:40

minimum price

play02:42

minimum

play02:47

and in this method i

play02:49

specify the

play02:51

parameter is the minimum price

play02:54

i use

play02:56

integer

play02:58

mean price

play03:00

and to write a

play03:02

custom relative query use the annotation

play03:05

query

play03:08

specify the query in the value attribute

play03:10

resist

play03:12

and you also need to specify the

play03:14

attribute native query equal to

play03:17

to trial spring that is api that

play03:20

this query is native it is not jpql

play03:25

and now

play03:26

we should try a

play03:28

sql statement

play03:31

select and ask the list

play03:33

select all

play03:35

from the

play03:36

products table know that this is sql

play03:38

statement so i use the table name

play03:41

which products instead of entity name

play03:44

product

play03:45

so

play03:46

with native query

play03:49

we should use the

play03:51

table name in the database

play03:54

it is not the entity name because the

play03:57

query is native

play03:59

where

play04:00

price

play04:02

greater than sorry

play04:05

whereby less than the

play04:08

argument

play04:10

here so i can use name parameter

play04:14

mean price to select only products

play04:19

having the price

play04:21

less than a specified amount

play04:26

sorry i changed the method to

play04:29

max price

play04:32

max price is

play04:34

here okay

play04:37

and then i update the test class to test

play04:40

the

play04:41

method

play04:42

that products with masterize

play04:45

it is using a native query as you can

play04:47

see

play04:48

okay i

play04:50

write another test method

play04:52

test

play04:54

public void test

play04:56

red

play04:58

products

play04:59

max price

play05:02

and i

play05:04

specify

play05:05

value for the max

play05:07

price is 1000 usd

play05:11

and call repo

play05:13

calls a method

play05:16

annotated with the native query

play05:20

products with mass

play05:22

price and it returns the list

play05:26

products

play05:27

list products

play05:31

and i bring each product in the return

play05:34

collection

play05:37

list products

play05:39

for each and i use

play05:42

laminar expression

play05:44

okay to bring each product object in the

play05:47

list collection

play05:49

okay now

play05:50

run this test method

play05:53

run next on the unit test

play06:02

you see the test is successful and it

play06:05

prints the

play06:07

product host price less than 1000 usd

play06:11

you see

play06:17

you see in the database we have some

play06:19

products always priced greater than 1000

play06:22

usd yeah

play06:24

and

play06:25

they are not included in the result here

play06:28

okay

play06:29

so that's a very

play06:31

simple example

play06:33

about writing

play06:35

and executing a native query with

play06:37

supporting data jpi you need to use the

play06:40

query annotation and specify the native

play06:43

query

play06:44

sql statement in the value attribute and

play06:47

know that you must specifies attribute

play06:50

native query equal to

play06:52

and in the native query you can also

play06:54

specify name parameter like this

play06:58

and this is a perfect example

play07:01

of using a native query

play07:03

you see

play07:05

the search method is annotated

play07:08

with the query annotation and this year

play07:11

native query for full text search

play07:15

it is

play07:16

specific to

play07:18

my sql database because the syntax match

play07:22

field names and awareness here

play07:25

is

play07:26

specific to mysql database only

play07:29

that's why

play07:31

we need to use a native query and

play07:33

specify the attribute native query equal

play07:36

to here

play07:37

and you can see that

play07:39

here i used

play07:41

name

play07:42

sorry indexed parameter

play07:44

the first parameter here uh so bring

play07:47

that data api we replaced the actual

play07:50

value of the first

play07:52

parameter in the method here keyword

play07:56

okay and you can also see i

play07:59

used bassinetion by passing the second

play08:02

parameter of thai

play08:03

pressure ball here

play08:06

and you see

play08:08

this is a service class

play08:11

where the search method is used here you

play08:14

see

play08:14

it creates a principle object

play08:18

specifies the best number as a

play08:20

number of results per best or number of

play08:23

items per page engine core repo dot

play08:26

search here

play08:30

passing the values of keyword and

play08:32

preservable object

play08:35

now let me start this springboard

play08:37

application

play08:38

to test the search query

play08:44

i want to print the sql statement

play08:50

social

play08:51

here okay

play08:53

okay the application

play08:55

has started

play08:57

and let me access is in chrome browser

play09:05

okay

play09:06

show me

play09:08

and and the keyword to search for

play09:10

example iphone

play09:12

you see the search result appears here

play09:16

and another keyword oh

play09:19

let me check the console

play09:26

let me search for the query

play09:29

match

play09:32

a rinsed

play09:41

okay you see this is a native query

play09:45

you see select asterisk from products

play09:48

where enable you could choose and match

play09:51

against

play09:52

and you can see it appends the limit

play09:55

class

play09:56

for pagination you see

play09:59

now let me type another keyword

play10:05

foreign

play10:20

now let's come back to this example and

play10:24

let me show you how to use uh

play10:25

presentation for this native query

play10:28

so just

play10:30

specify the second parameter of thai

play10:34

pleasurable or like this

play10:36

measurable from

play10:38

this package

play10:40

measurable

play10:41

and update the code for testing here

play10:44

before calling the method i need to

play10:47

create a new measurable object like this

play10:52

measurable equal based request

play10:58

and specifies the page number and

play11:01

the page size

play11:04

base number

play11:09

zero indicating the first best and the

play11:12

number of items purposed is five

play11:17

and passing the principal object in the

play11:20

method call here

play11:21

variable

play11:23

okay

play11:24

and

play11:26

run the test

play11:36

okay you see now it prints only the

play11:39

first best that contains five products

play11:43

you see

play11:45

this is a first patch

play11:48

and i can change the

play11:51

parameter

play11:52

argument here

play11:54

number one to

play11:56

show the items on the second page

play12:00

and run the test again

play12:09

and you see the products in the second

play12:12

press

play12:14

and now that you can

play12:16

specify the cal query which is used for

play12:20

the presentation in the annotation here

play12:25

for example uh specify the cal query

play12:30

query here which is used

play12:33

for the

play12:34

impersonation

play12:37

but by default you don't need to specify

play12:40

the card query and

play12:42

bring it as api that's the

play12:46

pagination

play12:47

under the scenes

play12:49

okay

play12:50

so this is account query

play12:53

and run the test again

play13:01

you see the same result

play13:08

next i'd like to show you how to

play13:11

code and execute a native update query

play13:16

okay so i want to

play13:18

code queries that updates the price of

play13:22

the products here

play13:24

so i declare a new method here public

play13:27

void update

play13:29

price

play13:31

with a parameter

play13:33

integer

play13:34

it is a

play13:37

amount

play13:39

and i used a

play13:41

query

play13:42

use a query annotation

play13:44

and specify the native query in the

play13:47

gb value

play13:49

and specify

play13:51

that it is the native query equal to

play13:55

and this is a update statement update

play14:00

products set

play14:02

price

play14:04

i want to increase the

play14:06

price my z amount

play14:09

amount

play14:10

okay you see

play14:13

and

play14:14

right unit test here

play14:22

test update price

play14:27

in this amount i want to increase

play14:31

the price of

play14:33

each product by

play14:35

two

play14:37

okay and call repo

play14:39

update price passing the

play14:42

amount number and run the test

play14:49

of course this is a

play14:51

very simple example

play14:53

you can do that

play14:54

with

play14:56

jpql okay we've got an error here

play15:00

you see

play15:03

is because for the update query

play15:07

we need to use

play15:10

an additional annotation

play15:13

it is the

play15:14

modifying annotation

play15:17

for the method and run the test again

play15:33

i think something wrong in the query

play15:37

it should be

play15:39

myself

play15:43

okay and run the test again

play15:52

okay so therefore you see it prints the

play15:55

update sql statement here

play15:58

and let me check the database

play16:02

you see all products

play16:04

price have been updated

play16:07

okay so that's

play16:11

some examples

play16:13

of

play16:14

coding using executing a native query

play16:17

with a spring data jpi

play16:21

okay so far you have learned what native

play16:24

query is when using a deep query and see

play16:27

some good examples using native query

play16:30

with spring itash api i hope you found

play16:32

this video helpful

play16:34

please subscribe to my channel like

play16:36

comment and share this video thanks for

play16:38

watching

Rate This

5.0 / 5 (0 votes)

Étiquettes Connexes
Spring Data JPANative QuerySQLMySQLJavaPaginationUpdate QueryCode ExampleDatabase QuerySoftware Tutorial
Besoin d'un résumé en anglais ?