1.解决方案
下面是mybatis查询语句,如果我们这次我们将 “state = ‘active’” 设置成动态条件,看看会发生什么。
<select id="findactivebloglike" resulttype="blog"> select * from blog where <if test="state != null"> state = #{state} </if> <if test="title != null"> and title like #{title} </if> <if test="author != null and author.name != null"> and author_name like #{author.name} </if> </select>
如果没有匹配的条件会怎么样?最终这条 sql 会变成这样:
select * from blog where
这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 sql 会是这样:
select * from blog where and title like ‘sometitle'
这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。
mybatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:
<select id="findactivebloglike" resulttype="blog"> select * from blog <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> and title like #{title} </if> <if test="author != null and author.name != null"> and author_name like #{author.name} </if> </where> </select>
where 元素只会在子元素返回任何内容的情况下才插入 “where” 子句。而且,若子句的开头为 “and” 或 “or”,where 元素也会将它们去除。
2.为什么不能使用1=1
1.会导致表中的数据索引失效
2.垃圾条件,没必要加
3.官方文档地址
到此这篇关于mybatis 为什么千万不要使用 where 1=1的文章就介绍到这了,更多相关mybatis where1=1内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
黄山市民网:https://www.huangshanshimin.com/