Bootstrap

MyBatis——查询

1 查询所有结果

MyBatis完成操作需要三步:编写接口方法->编写SQL->执行方法

2 查看详情

参数占位符:

#{}:会将其替换为 ? ,为了防止SQL注入

${}: 进行sql拼接,会存在SQL注入问题

使用时机:

*参数传递时:#{}

*对表名和列名进行动态设置时:${}  // 比较少 

<select id = "selectById" resultMap = "brandResultMap">
    select *
    from ${tbName} where id = #{id}

 parameterType:用于设置参数类型,该参数可以省略【了解,一般不写】

SQL语句中特殊字符的处理:①采用转义字符,例如:<  :  &lt;②<![CDATA[内容]]>

3 条件查询

分析:

1、条件表达式是什么?

2、如何连接各个条件表达式?

 

4 动态条件查询 

要求输入其中一个条件也能够实现查询

SQL语句随着用户的输入或外部条件的变化而变化,我们称为动态SQL

4.1 多条件动态查询——if

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <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>

语法结构:

<if test = “逻辑表达式”>

        条件表达式  // if 用于判断参数是否有值,使用 test 属性进行条件判断
问题:第一个条件不需要逻辑运算符
解决①:where后面加一个恒等式 使得后面的执行语句格式统一,都有and 

解决②:<where> 替代 where 关键字

4.2 单条件动态查询——choose(when、otherwise)

        从多个条件中选择一个使用,针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

choose ------------->  switch

when --------------->  case

otherwise ---------> default   

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

4.3 集合遍历——foreach

        在构建 IN 条件语句的时候

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

【注】可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach

当使用可迭代对象或数组时,index 是当前迭代的序号,item 值是本次迭代获取到的元素;当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值 。

;