MyBatis 动态SQL(*.xml)

原文参考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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,715评论 0 4
  • MyBatis 动态SQL 内容 Mybatis动态SQL在XML中支持的几种标签: if chose trim、...
    lihongyan阅读 8,421评论 1 10
  • MyBatis动态SQL 前言 在前面,我们已经学习了MyBatis的单表操作以及多表操作,在体验了MyBatis...
    颜洛滨阅读 1,768评论 2 47
  • GCD:一、基本概念1、同步:不开启新线程。省去了NSThread加同步锁的步骤。2、异步:可以开启新线程3、串行...
    早起的大艺术家阅读 173评论 0 0
  • 刚放学,牛牛急急忙忙地收拾了书包,向着学校门口跑去,他要和来接他回家的爷爷分享他的新梦想。 "爷爷!爷爷!我要当英...
    凶许的故事阅读 707评论 0 1