当前位置:网站首页>Landing guide for "prohibit using select * as query field list"
Landing guide for "prohibit using select * as query field list"
2022-07-02 04:17:00 【Mingmingruyue senior】
One 、 background
《 Alibaba Java Development Manual 》 MySQL Database part ,ORM The mapping part , talk about :
【 mandatory 】 In table query , Never use * List of fields as query , What fields are required must be clearly stated .
explain :
1) Increase query analyzer parsing cost .
2) It is easy to increase or decrease fields resultMap Inconsistent configuration .
3) Useless fields increase network consumption , In especial text Type field .
Even some companies scan the code , When you find code or MyBatis Appears in the configuration select * An alarm will be given to request modification .
The reason for this provision is explained in the specification , But when landing, you will encounter some choices .
Two 、 problem
Let's look at a positive example and a negative example .
Counter example :
UserDO getEmailById(Long id);
Corresponding xml sentence
<select id="getEmailById" parameterType="java.lang.Long" resultMap="resultMap">
SELECT * FROM user WHERE id = #{id}
</select>
Example :
String getEmailById(Long id);
Corresponding xml sentence :
<select id="getEmailById" parameterType="java.lang.Long" resultType="java.lang.String">
SELECT email FROM user WHERE id = #{id}
</select>
As the manual says , The advantage of this way of writing is :
1) Increase query analyzer parsing cost .
2) It is easy to increase or decrease fields resultMap Inconsistent configuration .
3) Useless fields increase network consumption , In especial text Type field .
It's strange that , Many articles end here at most .
It ended like this ???
So what if you query some fields ? Is to continue to use UserDO Or define a new DO class ?
【1】 Continue to use UserDO Return value as method :
<< advantage >>:
Save trouble , Reduce object definitions
<< shortcoming >>:
It is impossible to know exactly which properties are assigned and which are not assigned according to the function name or return value .
【2】 Define a new DO object
<< advantage >>:
1) Can be based on the method name and return value , Clearly perceive the fields obtained by the current business
2) Special queries are well distinguished from general queries
<< shortcoming >>:
When there are many scenes , Need to define DO Too many objectsSuch as user Table has 20 A field ,A Business needs to query 18 A field ,B Business needs 8 A field ,C The business needs all fields ,D Business needs 5 A field ,E Business needs 7 A field, etc , And these scenes are based on ID The query .
3、 ... and 、 Choose
3.1 Big logic
1) Generally, check more fields , There's not much difference in performance
2) A lot of scenarios , Performance is not the most important factor in our decision , Code readability 、 Maintainability is very important
3) Keep doing the right thing when coding , Not how easy it is to come
4) The code should conform to some principles of design patterns , High cohesion and weak coupling
3.2 analogy
【1】 If you are the caller of the interface , The service provider provides you with an interface , Back to DTO There are 10 A field , You just need one of them 2 A field , You ask the other party to provide a new interface , Just return to this 2 A field ? Although this is better , But this is not usually done in practice .
If you need 2 A field , He needs to 3 A field , Another person also needs 3 There are two fields, but the fields are different , Define new interfaces , The service provider is going to crash .
Another example is in domain driven design , Domain object ( Such as User ) Not because the upstream anti-corrosion coating requires several properties , And return different proprietary domain objects .
Such as << You go to the market to buy vegetables >> This scene , Vegetable farmers can't because you just need 2 An egg , On the booth, there can only be 2 An egg . He usually puts everything out , You choose according to your needs .
Such as << You go to the Internet platform to buy vegetables >> The scene of the rider delivering vegetables , At this point, for the current order , Only the corresponding quantity of vegetables should be sent to you , Instead of bringing all the dishes in the supermarket , When it's delivered to your door , Then put it all out , Let you count yourself on the spot .

【2】 If you rely on two-party services to return you a full DTO, Let you call according to the method name “ guess ” Which attributes will be assigned ( Don't look at his source code , How do you know what is assigned and what is not assigned ), Isn't it terrible ?
If you put a whole DTO Or generic VO To the front end , There is no guarantee that all properties are assigned , Let him go according to the called method “ guess ” Which attributes of the current scene have been assigned , Isn't it terrible ?
Maybe some students may say , It's OK to make a document agreement .
But , What could be more appropriate than a convention between parameters and return values ?
Any subsequent changes should be added or deleted ?
How to maintain codes after personnel changes ?
There are usually two options :
(1) Provide a large and comprehensive , Make sure that some fields are assigned , Upstream on demand ;
(2) Provide a dedicated object , The assigned fields are in the properties of this object .
3.3 Conclusion
【 recommend 】 If it is clear in business that only some fields are required , You can use a common interface to get all fields , Then, the upper layer can only use the required fields .
[1] If the query criteria are indexed , The query field does not contain large fields , The performance difference between querying a single field and querying multiple fields is negligible .
[2] The traditional three-tier architecture , The anticorrosive layer invokes the service layer 、 The service layer invokes the data access layer , In part to reuse . Use the general query interface ( adopt id Get the entire DO object ), Code reuse can be realized to a greater extent .[2.1] As mentioned above, different businesses need different numbers of fields , Defining six or seven objects is cumbersome , Business needs should be in DTO perhaps VO Level control field ,DO Layers can be reused .
[2.2] If your business VO Need downstream services 3 A field , Then you ask the downstream service to provide you alone and only return this 3 Of fields DTO/ BO ?? Obviously unreasonable ?
[2.3] You should not let every query scenario affect DAO layer , If so , So what is the meaning of layering ?
【 recommend 】 If you need to customize the query , Function names cannot be ambiguous , To reflect the business meaning ; General purpose is not allowed DO object , Need to use a packaging type or define a proprietary DO .
Counter example :UserDO getUserDetailById(Long id)
The method name here is right “ The user details page requires fields ” Business description of , still “ All user fields ” Description of ?
UserDO getUserEmailById(Long id)
If the caller code is long , Use later UserDO when “ Always remember ” This UserDO Only email This property has a value .
Example :String getEmailById(Long id)UserSimpleDO getSimpleById(Long id)
[1] If you use ambiguous class generalized function names , The return value is generic DO, The user can easily misuse .
[2] establish DO It's not a lot of work , Objects can also be converted through tool classes .
[3] Comply with the interface isolation principle ,“ Using multiple specialized interfaces , Instead of using a single master interface , That is, the client should not rely on interfaces it does not need ” Switch down “ You should not rely on unnecessary fields ”
[4] According to Dimitar's law Talk only to your immediate friends and not to strangers The fields required by the current business are immediate friends, The other fields are strangers , Consistent with high cohesion 、 Weak coupling software design principleimagine If
UserDO getSimpleById(Long id)That's the definition , You don't see mybatis Of xml You know how many properties have been valued ?
Which method should the caller use , Focus on parameters and return values , Should not be “ Forced to ” To understand the underlying implementation .
Four 、 summary
When we make a choice , Some typical principles of software design should be kept in mind , Such as high cohesion 、 Weak coupling ; Several principles of design patterns : Single responsibility 、 High cohesion and weak coupling 、 Richter replacement 、 Interface isolation 、 Dimitar's law ; Reduce complexity and so on .
Insist on doing the right thing , Not how easy it is to come .
Readability cannot be sacrificed for performance , Maintainability .
It's not easy to create , If this article helps you , Welcome to thumb up 、 Collection and attention , Your support and encouragement , It's the biggest driving force of my creation .
边栏推荐
- Introduction to JSON usage scenarios and precautions
- Where can I buy cancer insurance? Which product is better?
- Is it safe to open an account with first venture securities? I like to open an account. How can I open it?
- powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
- Pytorch-Yolov5从0运行Bug解决:
- 阿里云polkit pkexec 本地提权漏洞
- Www2022 | know your way back: self training method of graph neural network under distribution and migration
- XSS prevention
- MySQL error: expression 1 of select list is not in group by claim and contains nonaggre
- 藍湖的安裝及使用
猜你喜欢

What is 5g industrial wireless gateway? What functions can 5g industrial wireless gateway achieve?

The confusion I encountered when learning stm32

Common sense of cloud server security settings

Pytorch---使用Pytorch进行鸟类的预测

初识P4语言

Play with concurrency: what's the use of interruptedexception?

How much is the tuition fee of SCM training class? How long is the study time?

Opencv learning example code 3.2.4 LUT

Force buckle 540 A single element in an ordered array

阿里云polkit pkexec 本地提权漏洞
随机推荐
Pandora IOT development board learning (RT thread) - Experiment 1 LED flashing experiment (learning notes)
Where can I buy cancer insurance? Which product is better?
Wechat applet calculates the distance between the two places
Pytorch yolov5 exécute la résolution de bogues à partir de 0:
[untitled]
Suggestions on settlement solution of u standard contract position explosion
手撕——排序
Li Kou interview question 02.08 Loop detection
【c语言】基础篇学习笔记
Wechat applet JWT login issue token
pip 安装第三方库
Pytoch yolov5 runs bug solution from 0:
PR zero foundation introductory guide note 2
Recyclerview add header
Bitmap principle code record
Go branch and loop
藍湖的安裝及使用
Uni app - realize the countdown of 60 seconds to obtain the mobile verification code (mobile number + verification code login function)
Www 2022 | rethinking the knowledge map completion of graph convolution network
Raspberry pie GPIO pin controls traffic light and buzzer
