当前位置:网站首页>@Query difficult and miscellaneous diseases
@Query difficult and miscellaneous diseases
2022-06-26 02:13:00 【InfoQ】
author :Damon
Blog :
http://www.damon8.cn
Make a friend of the ape world | Microservices | Containerization | automation
Quick experience @Query Methods
Before the start , First of all, let's take a look at Demo, Follow our previous example , Add a new one @Query Methods , Have a quick experience @Query How to use , As shown below :
package com.example.jpa.example1;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserDtoRepository extends JpaRepository<User,Long> {
// adopt query Annotation basis name Inquire about user Information
@Query("From User where name=:name")
User findByQuery(@Param("name") String nameParam);
}
then , We add a new test class :
package com.example.jpa.example1;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
public class UserRepositoryQueryTest {
@Autowired
private UserDtoRepository userDtoRepository;
@Test
public void testQueryAnnotation() {
// Add a new piece of data to facilitate the test userDtoRepository.save(User.builder().name("jackxx").email("[email protected]").sex("man").address("shanghai").build());
// Call the above method to view the result
User user2 = userDtoRepository.findByQuery("jack");
System.out.println(user2);
}
}
Last , See the results of the operation as follows :
Hibernate: insert into user (address, email, name, sex, version, id) values (?, ?, ?, ?, ?, ?)
Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.email as email3_0_, user0_.name as name4_0_, user0_.sex as sex5_0_, user0_.version as version6_0_ from user user0_ where user0_.name=?
User(id=1, name=jack, [email protected], version=0, sex=man, address=shanghai)
Through the above example, we find that , This time, the query syntax is not generated by the method name , It is @Query Annotations play a role , send "From User where name=:name"JPQL It works . So what is its implementation principle ? Let's take a look at the source code .
JpaQueryLookupStrategy Key source code analysis
We are 03 The class has already introduced QueryLookupStrategy What are the policy values for , So let's take a look at how the source code works .
Let's open it first QueryExecutorMethodInterceptor class , Find the following code :

Then run the above test case , At this time, set a breakpoint here , You can see that the default policy is CreateIfNotFound, That is, if there is @Query annotation , So in order to @Query The contents of the notes shall prevail , Method names can be ignored .
Let's keep looking back , Enter into lookupStrategy.resolveQuery Inside , As shown below :

Through the breakpoints and red boxes in the above figure , We also found ,Spring Data JPA This place uses a strategy 、 Pattern , We can also refer to it when we write our own strategy patterns .
Then go on down debug, Enter into resolveQuery Method inside , As shown in the figure below :

We can see in the picture ① It's about , If Query Notes found , You don't get to ② It's too late ( That is, our No 03 In class Defined Query Method grammar ).
At this time we click on Query Inside Query Take a look at the value of the property , You will find that there are two SQL: One is the total number of queries Query Definition , The other is the query results Query Definition .
By now we have basically understood , If you want to see it Query How is it generated 、 above @Param How annotations work , It can be seen in the figure above ① It's about debug Keep looking inside , As shown below :

We continued our journey debug You can see how to pass @Query To generate SQL 了 , This is not the point of this section , I've simply mentioned it here , You can go by yourself if you are interested debug to glance at .
So we have the principle , So let's see @Query Give us some grammar , Let's look at the basic usage first .
@Query The basic usage of
Before explaining its grammar , Let's take a look at its annotation source code , Learn the basic usage .
package org.springframework.data.jpa.repository;
public @interface Query {
/**
* Appoint JPQL Query statement .(nativeQuery=true When , It's original. Sql sentence )
*/
String value() default "";
/**
* Appoint count Of JPQL sentence , If not specified, it will be based on query Automatic generation .
* ( If so nativeQuery=true When , It means the original Sql sentence )
*/
String countQuery() default "";
/**
* According to which field count, General default .
*/
String countProjection() default "";
/**
* The default is false, Express value Is it native sql sentence
*/
boolean nativeQuery() default false;
/**
* You can specify one query Name , Must be unique .
* If you don't specify , The default generation rule is :
* {$domainClass}.${queryMethodName}
*/
String name() default "";
/*
* You can specify one count Of query Name , Must be unique .
* If you don't specify , The default generation rule is :
* {$domainClass}.${queryMethodName}.count
*/
String countName() default "";
}
So here you will find , @Query The usage is to use JPQL Create declarative query methods for entities . We usually just need to care about @Query Inside value and nativeQuery、countQuery The value of the can , Because others are not often used .
Use declarative JPQL There is a benefit of querying , Is to know whether your grammar is correct when you start . So let's briefly introduce JPQL grammar .
JPQL The grammar of
Let's first look at the syntax of the query , The code is as follows :
SELECT ... FROM ...
[WHERE ...]
[GROUP BY ... [HAVING ...]]
[ORDER BY ...]
You will find that its grammatical structure is a bit similar to ours SQL, The only difference is JPQL FROM Followed by the object , and SQL The fields in the object correspond to the attribute fields in the object .
Similarly, let's take a look at update and delete The grammatical structure of :
DELETE FROM ... [WHERE ...]
UPDATE ... SET ... [WHERE ...]
among “...” The omitted parts are the entity object name and the field name in the entity object , And it is similar to SQL The same syntax keywords include :SELECT FROM WHERE UPDATE DELETE JOIN OUTER INNER LEFT GROUP BY HAVING FETCH DISTINCT OBJECT NULL TRUE FALSE NOT AND OR BETWEEN LIKE IN AS UNKNOWN EMPTY MEMBER OF IS AVG MAX MIN SUM COUNT ORDER BY ASC DESC MOD UPPER LOWER TRIM POSITION CHARACTER_LENGTH CHAR_LENGTH BIT_LENGTH CURRENT_TIME CURRENT_DATE CURRENT_TIMESTAMP NEW EXISTS ALL ANY SOME So much , Let's not introduce one by one .
边栏推荐
- Connecting the projector
- Calibration...
- A lost note for konjaku beginner
- The first intimate contact of caching technology
- WPF 窗口居中 & 变更触发机制
- 创建OpenGl窗口
- vtk初始化代码学习1
- 深度好文:什么是超网 Supernetting?
- Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) D. Felicity‘s Big Secret Revealed
- A solution to cross domain problems
猜你喜欢
随机推荐
ARM流水线如何提高代码执行效率
Computer shortcut keys commonly used by experts
记录一个诡异的图片上传问题
vscode调试时提示更新到最新调试版本
Fastadmin applet assistant is purchased, but the work order cannot be published in the problem work order
WPF 窗口居中 & 变更触发机制
Is the securities account recommended by qiniu safe?
FPGA实现图像二值形态学滤波——腐蚀膨胀
Sqlyog shortcut keys
Markov decision process (MDP): gambler problem
Three factors affecting personal growth
SDRAM控制器——仲裁模块的实现
Jenkins localization and its invalid solution
The first intimate contact of caching technology
Create OpenGL window
工作一年闲记
Snake game
vtk初始化代码学习1
vs2015+PCL1.8.1+qt5.12-----(1)
缓存技术之第一次亲密接触









