当前位置:网站首页>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 .
边栏推荐
- Actual combat | use composite material 3 in application
- SQL: common SQL commands
- Installation et utilisation du lac bleu
- LxC limits the number of CPUs
- Yyds dry inventory compiler and compiler tools
- 蓝湖的安装及使用
- 千亿市场规模医疗美容行业的水究竟有多浑?
- Lei Jun wrote a blog when he was a programmer. It's awesome
- Which is better, industrial intelligent gateway or edge computing gateway? How to choose the right one?
- [JS event -- event flow]
猜你喜欢
云服务器的安全设置常识
A summary of common interview questions in 2022, including 25 technology stacks, has helped me successfully get an offer from Tencent
FAQ | FAQ for building applications for large screen devices
"No war on the Western Front" we just began to love life, but we had to shoot at everything
10 minutes to understand CMS garbage collector in JVM
Finally got byte offer. The 25-year-old inexperienced perception of software testing is written to you who are still confused
Typescript practice for SAP ui5
Pytoch --- use pytoch to predict birds
Hands on deep learning (II) -- multi layer perceptron
Federal learning: dividing non IID samples according to Dirichlet distribution
随机推荐
Fingertips life Chapter 4 modules and packages
Lei Jun wrote a blog when he was a programmer. It's awesome
Spring moves are coming. Watch the gods fight
Installation et utilisation du lac bleu
Feature Engineering: summary of common feature transformation methods
Realizing deep learning framework from zero -- Introduction to neural network
Sword finger offer II 006 Sort the sum of two numbers in the array
Déchirure à la main - tri
There is no prompt for SQL in idea XML, and the dialect setting is useless.
okcc为什么云呼叫中心比传统呼叫中心更好?
Pytoch --- use pytoch for image positioning
Go variables and constants
整理了一份ECS夏日省钱秘籍,这次@老用户快来领走
[JS -- map string]
XSS prevention
cookie、session、tooken
Use of go package
The first practical project of software tester: web side (video tutorial + document + use case library)
Suggestions on settlement solution of u standard contract position explosion
藍湖的安裝及使用