当前位置:网站首页>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
边栏推荐
- Caddy server agent
- On Data Mining
- [combinatorics] exponential generating function (example of exponential generating function solving multiple set arrangement)
- [combinatorics] generating function (example of generating function | calculating generating function with given general term formula | calculating general term formula with given generating function)
- How to expand the capacity of golang slice slice
- Module 9 operation
- 毕业总结
- Install apache+php+mysql+phpmyadmin xampp and its error resolution
- Unity2018 to wechat games without pictures
- Setinterval CPU intensive- Is setInterval CPU intensive?
猜你喜欢
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
2022-2028 global physiotherapy clinic industry research and trend analysis report
Unity webgl optimization
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
What problems can cross-border e-commerce sellers solve with multi platform ERP management system
English语法_名词 - 分类
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
Multifunctional web file manager filestash
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Bidding procurement scheme management of Oracle project management system
随机推荐
TypeScript 官网教程
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
Computer graduation design PHP campus address book telephone number inquiry system
Opencv learning notes (continuously updated)
Reappearance of ASPP (atlas spatial pyramid pooling) code
Naoqi robot summary 27
Use of unsafe class
AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]
[linux]centos 7 reports an error when installing MySQL "no package MySQL server available" no package ZABBIX server MySQL available
SSH 远程执行命令简介
Analysis of the reasons why enterprises build their own software development teams to use software manpower outsourcing services at the same time
How to disable the clear button of ie10 insert text box- How can I disable the clear button that IE10 inserts into textboxes?
2022-2028 global marking ink industry research and trend analysis report
Win32: dump file analysis of heap corruption
Theoretical description of linear equations and summary of methods for solving linear equations by eigen
2022-2028 global physiotherapy clinic industry research and trend analysis report
Bloom filter [proposed by bloom in 1970; redis cache penetration solution]
[Yu Yue education] world reference materials of Microbiology in Shanghai Jiaotong University
Okaleido, a multimedia NFT aggregation platform, is about to go online, and a new NFT era may come
SDNUOJ1015