当前位置:网站首页>Suffix derivation based on query object fields
Suffix derivation based on query object fields
2022-07-03 18:36:00 【f0rb】
Suffix derivation based on query object fields
Continued 《SpringDataJPA From introduction to abandonment 》
The new problem
The previous chapter talked about how to Query Class field plus @QueryField
Annotation to map fields to SQL Query criteria for statement , But when there are more and more query conditions , our UserQuery
Class will probably become like this :
public class UserQuery extends PageQuery {
@QueryField(and = "username = ?")
private String username;
@QueryField(and = "nickname = ?")
private String nickname;
@QueryField(and = "email = ?")
private String email;
@QueryField(and = "valid = ?")
private Boolean valid;
@QueryField(and = "nickname LIKE CONCAT('%', ?, '%')")
private String nicknameLike;
@QueryField(and = "email LIKE CONCAT('%', ?, '%')")
private String emailLike;
}
At this time, we can find some problems : Each field needs to be added @QueryField
annotation , It seems that a lot of repetitive code has been written . So can we simplify it ?
Then let's try to continue refactoring .
Continue refactoring
go through UserQuery
Class definition will find some fields @QueryField
Annotated and The value format of variable definition is similar , All are <column> = ?
, And here it is <column>
And the name of the field variable is the same , So we can private String <field>;
The corresponding query statement is directly derived from the variable name in , such as private String username
, Take out username
Plus = ?
Immediate username = ?
.
Then the corresponding processing logic evolves as follows :
Traverse Query All fields of the object , For all not null Field of : If you define @QueryField
annotation , Just addand
Defined query statement ;If there's no definition @QueryField
annotation , Is to add query statements<feild> = ?
.
The core code is roughly as follows :
private void appendAnd(List<String> whereList, Field field) {
QueryField queryField = field.getAnnotation(QueryField.class);
- whereList.add(queryField.and());
+ if (queryField != null) {
+ whereList.add(queryField.and());
+ } else {
+ whereList.add(field.getName() + " = ?");
+ }
}
And ours UserQuery
Class can be simplified as follows ,
public class UserQuery extends PageQuery {
private String username;
private String nickname;
private String email;
private Boolean valid;
@QueryField(and = "nickname LIKE CONCAT('%', ?, '%')")
private String nicknameLike;
@QueryField(and = "email LIKE CONCAT('%', ?, '%')")
private String emailLike;
}
So here comes the question ,LIKE Can the query also be optimized ?
Analysis will find this LIKE Statements can also be passed through field names emailLike
Split to get query email LIKE ?
, Then the string is spliced into %value%
The format of , Replace CONCAT
function . such LIKE Queries do not need to be added @QueryField
Note the .
So we have such an idea , It is to name fields as column names plus specific suffixes , When the field value is not null when , The corresponding query statement and query parameters are derived from the field name and field value .
Suffix derivation
Through the previous analysis , We can define from the field private String username;
It is deduced that username = ?
, from private String emailLike
It is deduced that email LIKE ?
, This is a SQL Two query conditions commonly used in statements , that :
IN How to deal with queries ?
IN The characteristic of query is that the parameter is a list , Length is not fixed , Therefore, we need to determine the number of placeholders according to the number of input parameters .
about IN Inquire about , Also, first define the field as the form of column name plus suffix , such as idIn
, Suppose a length of 3 A list of , So from idIn
Introduction id IN
, From the parameter, the placeholder is ?, ?, ?
, Add parentheses and splice them together , Immediate id IN (?, ?, ?)
.
When the length of the incoming list is 0 when , You need to define the query statement as
id IN (null)
, And field is null Time is handled differently .
IS NULL How to deal with it ?
IS NULL
Query is characterized by no parameters , It is not suitable to define specific types for fields , It is not suitable to determine whether the field value is null To determine whether to generate a query statement for this field .
One solution is to define it as boolean
type , The default is false
, No processing , When the value is set to true
when , To generate query statements , namely idNull
The assignment is true
when , The corresponding query criteria are deduced as id IS NULL
.
Then there is also. NOT LIKE
, NOT IN
, >
, <
How about these ?
These query conditions are much the same , Here is a table , List the suffixes and processing methods corresponding to the query conditions .
Suffix name | The operator | Place holder | Type restrictions | Value processing |
---|---|---|---|---|
- | = | ? | ||
Not | != | ? | ||
NotLike | NOT LIKE | ? | String | %value% |
Like | LIKE | ? | String | %value% |
Start | LIKE | ? | String | %value |
End | LIKE | ? | String | value% |
NotIn | NOT IN | When the set is not empty :(?[, ?]) | Collection | |
In | IN | When the set is not empty :(?[, ?]) | Collection | |
NotNull | IS NOT NULL | - | boolean | |
Null | IS NULL | - | boolean | |
Gt | > | ? | ||
Ge | >= | ? | ||
Lt | < | ? | ||
Le | <= | ? | ||
Eq | = | ? |
So our UserQuery
Class can be defined to map query statements :
public class UserQuery extends PageQuery {
private Integer id;
private Integer idGt;
private Integer idGe;
private Integer idLt;
private Integer idLe;
private List<Integer> idIn;
private List<Integer> idNotIn;
private String username;
private String usernameLike;
private String usernameStart;
private boolean emailNull;
private boolean emailNotNull;
}
perfect .
Keep asking questions
The above passage is right UserQuery
Class optimization , Established SQL Suffix derivation scheme of query conditions , It greatly simplifies the development of database dynamic query code .
however , Here comes the question , How to deal with the following complex nested queries ?
SELECT * FROM t_perm WHERE id IN (
SELECT permId FROM t_role_and_perm WHERE roleId IN (
SELECT roleId FROM t_user_and_role WHERE userId IN (
SELECT id FROM t_user WHERE username = ?
)))
The next part will be explained
边栏推荐
- [combinatorics] exponential generating function (proving that the exponential generating function solves the arrangement of multiple sets)
- Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up
- Win32: dump file analysis of heap corruption
- Read the paper glodyne global topology preserving dynamic network embedding
- Have you learned the correct expression posture of programmers on Valentine's day?
- 2022-2028 global scar care product industry research and trend analysis report
- Shell script return value with which output
- Torch learning notes (2) -- 11 common operation modes of tensor
- The number of incremental paths in the grid graph [dfs reverse path + memory dfs]
- Win32: analyse du fichier dump pour la défaillance du tas
猜你喜欢
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
Win32: dump file analysis of heap corruption
How to quickly view the inheritance methods of existing models in torchvision?
Win 11 major updates, new features love love.
What kind of experience is it when the Institute earns 20000 yuan a month?
4. Load balancing and dynamic static separation
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
An academic paper sharing and approval system based on PHP for computer graduation design
Computer graduation design PHP sports goods online sales system website
English语法_形容词/副词3级 - 倍数表达
随机推荐
English语法_形容词/副词3级 - 倍数表达
统计图像中各像素值的数量
The number of incremental paths in the grid graph [dfs reverse path + memory dfs]
Redis cache avalanche, penetration, breakdown
12、 Service management
There are several levels of personal income tax
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University
ES7 - Optimization of promise
Have you learned the correct expression posture of programmers on Valentine's day?
What problems can cross-border e-commerce sellers solve with multi platform ERP management system
Count the number of pixel values in the image
MySQL duplicate check
English語法_名詞 - 分類
How to quickly view the inheritance methods of existing models in torchvision?
[combinatorics] generating function (use generating function to solve the combination number of multiple sets R)
The vscode code is automatically modified to a compliance code when it is formatted and saved
webcodecs
Torch learning notes (6) -- logistic regression model (self training)
After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试