mybatis动态sql(常用)

mybatis常见元素

  • cache – 该命名空间的缓存配置。
  • cache-ref – 引用其它命名空间的缓存配置。
  • resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
  • sql – 可被其它语句引用的可重用语句块。
  • insert – 映射插入语句。
  • update – 映射更新语句。
  • delete – 映射删除语句。
  • select – 映射查询语句。
<insert id="insertAuthor">
  insert into Author (id,username,password,email,bio)
  values (#{id},#{username},#{password},#{email},#{bio})
</insert>

<update id="updateAuthor">
  update Author set
    username = #{username},
    password = #{password},
    email = #{email},
    bio = #{bio}
  where id = #{id}
</update>

<delete id="deleteAuthor">
  delete from Author where id = #{id}
</delete>

select

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>
  • 语句的名字是selectPerson
  • 接收一个int/Integer的类型参数
  • 返回一个 HashMap 类型的对象

动态sql

  1. if
  2. choose (when, otherwise)
  3. trim (where, set)
  4. foreach

if使用

动态 SQL 最常见情景是根据条件包含 where 子句的一部分

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
  • 如果不传入title整个blog将会返回
  • 如果传入,将模糊查询对应"title"对应的一列
    如果又想加入一个条件查询"author",写法如下
<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>

choose使用

  • 当我们在众多条件中使用一个的时候,使用choose
  • 类似我们使用的swich语句
<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>

上述两种方法还是有诟病,比如没有匹配的条件,那么就会出现如下的样子

SELECT * FROM BLOG
WHERE
SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

这样就产生了set关键字

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>
  • 这样我们就可以实现只包含需要更新的列,忽略其它不更新的列
<update id="updUser" parameterType="user">
update usertable
<!--
prefix: 前缀, 表示向前面添加内容
prefixOverrides: 从前面删除内容
suffix: 后缀, 表示向后面添加内容
suffixOverrides: 从后面删除内容
-->

foreach

  • 对集合元素遍历
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

参考mybatis文档https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

posted @ 2021-07-08 14:45  xiaoff  阅读(81)  评论(0编辑  收藏  举报