MyBatis 动态SQL(*.xml)

2018-10-21  本文已影响0人  一杉风雨

原文参考MyBatis 动态SQL

MyBatis的动态SQL大大减少了拼接SQL语句时候的各种格式问题,这里摘录些主要的用法。

  1. IF
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  WHERE state = ‘ACTIVE’ 
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
  1. CHOOSE-WHEN-OHTERWIRSE
<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>
  1. TRIM
# <where>
<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>相当于
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>
# <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>

# 这了的<set>相当于
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
  1. FOREACH
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
上一篇 下一篇

猜你喜欢

热点阅读