Spring Data JPA : How to write custom query by JpaRespository | Native Query

Описание к видео Spring Data JPA : How to write custom query by JpaRespository | Native Query

#JpaRespository #CustomQuery
► Java: Write custom query with @Query & @NamedQuery annotation by Spring Data JPA
► SUBSCRIBE & LIKE!!
► Official Email Id: [email protected]
► Download the sample java microservice application :
https://github.com/admindebu/In-Memor...
► Follow on Facebook:   / techtalkdebu  
► Follow on LinkedIn:   / debu-paul  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
► Here is our amazing playlist for Core Java, Spring MVC/Boot, Git and Micro service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Core Java ::    • Exception in Java detail explanation ...  
2. Spring MVC & Spring Boot ::    • Quick Start Spring Boot project with ...  
3. Micro Service ::    • Micro Service - Monolithic vs Micro s...  
4. Git/GitHub ::    • VCS - What is GitHub and Create an Ac...  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Watch my "Most Watched Videos"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
► HTTPS & HTTPS protocol ::    • What is HTTP Protocol and Different H...  

Playlist :    • Core Java Interview Questions - Diffe...   Tutorial for beginners with examples, Interview Questions and Concepts.

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute.

The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.

It's a good approach to place a query definition just above the method inside the repository rather than inside our domain model as named queries. The repository is responsible for persistence, so it's a better place to store these definitions.

2.1. JPQL
By default the query definition uses JPQL.

Let's look at a simple repository method that returns active User entities from the database:

@Query("SELECT u FROM User u WHERE u.status = 1")
Collection(User) findAllActiveUsers();

Please note: if you are using JPQL then you have to provide the exact Entity name in the entity class. else you will get below exception :
org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped
Spring, Spring Data JPA: org.hibernate.hql.internal.ast.QuerySyntaxException: Test is not mapped

Native
We can use also native SQL to define our query. All we have to do is to set the value of the nativeQuery attribute to true and define the native SQL query in the value attribute of the annotation:

@Query(
value = "SELECT * FROM UserDetails u WHERE u.status =?1",
nativeQuery = true)
Collection(UserDetails) findAllActiveUsersNative();

Regards,
Debu Paul

Комментарии

Информация по комментариям в разработке