mybatis 为什么千万不要使用 where 1=1

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 BLOGWHERE

这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

SELECT * FROM BLOGWHEREAND 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官网地址

到此这篇关于mybatis 为什么千万不要使用 where 1=1的文章就介绍到这了,更多相关mybatis where1=1内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

并且如此真实的活着——这,就是旅行的意义。

mybatis 为什么千万不要使用 where 1=1

相关文章:

你感兴趣的文章:

标签云: