当前位置:网站首页>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 @QueryFieldannotation , Just addandDefined query statement ;If there's no definition @QueryFieldannotation , 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
边栏推荐
- Real time split network (continuous update)
- Class exercises
- Image 24 bits de profondeur à 8 bits de profondeur
- An academic paper sharing and approval system based on PHP for computer graduation design
- On Data Mining
- What London Silver Trading software supports multiple languages
- There are several levels of personal income tax
- 2022-2028 global solid phase extraction column industry research and trend analysis report
- webcodecs
- [untitled]
猜你喜欢

2022-2028 global plasmid DNA cdmo industry research and trend analysis report

Redis cache avalanche, penetration, breakdown

Naoqi robot summary 27

What is SQL get connection
![[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University](/img/52/b97c618a8f2eb29ad0ccca221bb5c1.jpg)
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University

NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线

Caddy server agent
![[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)](/img/50/f89092b492d0138304209a72ff05b4.jpg)
[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)

多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临

Computer graduation design PHP sports goods online sales system website
随机推荐
Raft 日志复制
2022-2028 global lithium battery copper foil industry research and trend analysis report
How to track the real-time trend of Bank of London
Read the paper glodyne global topology preserving dynamic network embedding
[combinatorics] exponential generating function (concept of exponential generating function | permutation number exponential generating function = combinatorial number ordinary generating function | e
Grammaire anglaise Nom - Classification
Torch learning notes (7) -- take lenet as an example for dataload operation (detailed explanation + reserve knowledge supplement)
[linux]centos 7 reports an error when installing MySQL "no package MySQL server available" no package ZABBIX server MySQL available
Module 9 operation
What does foo mean in programming?
Line by line explanation of yolox source code of anchor free series network (5) -- mosaic data enhancement and mathematical understanding
English grammar_ Noun classification
What kind of experience is it when the Institute earns 20000 yuan a month?
An academic paper sharing and approval system based on PHP for computer graduation design
What is SQL get connection
Win 11 major updates, new features love love.
Redis core technology and practice - learning notes (11): why not just string
Software development freelancer's Road
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University
Theoretical description of linear equations and summary of methods for solving linear equations by eigen