Recently, I took over an old project. The "pleasant mood" was naturally nothing to say. Friends who made development knew that I won't say much here, it's tears ...
If you take over the old project, you must first get familiar with the business code. However, when you read the Mapper file, you find a more weird thing.Here is a simplified business code:
The witty partner may have seen the problem, and found the same imagination among many mapper. Almost all Mapper contains a useless stitching SQL: where 1 = 1.As a person with almost code cleaning, he can't help but transform it.
Since the where 1 = 1 is removed, the easiest way is to delete it directly from the code, as shown in the following code:
The above code is deleted by 1 = 1, and removes the first name query to prevent the error from the SQL query.
But is this okay?Let's look at the results directly, when the parameter name query is included, the result is as follows:
Everything goes smoothly, a perfect mess.
However, when omitting the name parameter (because name is a non -necessary parameter, it can be omitted), which can cause the following abnormalities:
或仅在有密码查询时,结果是相同的:
这是所有错误的信息。我该怎么办?您可以还原1 = 1返回吗?
实际上,无需,我已经在Mybatis中考虑了这个问题。我们可以用Mybatis中的标签替换SQL中的关键字,并在每个标签中添加一个和拼布。这个问题得到了解决。如以下代码中所示,以下代码分类:
代码转换完成后,让我们测试所有请求方案。
目前,我们无法传递任何参数(查询所有数据),如下图所示:
生成的SQL语句如下:
您也可以按名称传递1个参数,如下图所示:
生成的SQL如下图所示:
您也只能根据密码查询,如下图所示:
生成的SQL如下图所示:
您也可以根据名称和密码进行联合查询,如下图所示:
生成的SQL如下图所示:
我们惊讶地发现,使用标签后,是否是任何查询场景,一个或多个参数传递,或直接传递任何参数。
首先,该标签将被评判。如果没有参数,它将不会拼接SQL语句中的查询,否则在缝合查询时会拼接。其次,在查询labeldelete中,第一个条件前面的关键字和关键字不会导致SQL语法错误。这也在官方文档中解释了,如下图所示:
在Mybatis中,建议避免使用毫无意义的SQL缝合,其中1 =1。我们可以使用标签替换1 = 1的标签。此写作简单而优雅。为什么不呢?上面的内容只是个人观点。欢迎留言进行讨论。
请注意公共帐户“ Java中国社区”,以获取更多Mybatis和Spring Boot系列文章。