美文网首页
MyBatis 动态SQL(*.xml)

MyBatis 动态SQL(*.xml)

作者: 一杉风雨 | 来源:发表于2018-10-21 15:31 被阅读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>

相关文章

  • MyBatis动态SQL

    MyBatis 动态SQL 内容 Mybatis动态SQL在XML中支持的几种标签: if chose trim、...

  • 动态 SQL

    根据不同的条件需要执行不同的 SQL 命令.称为动态 SQL MyBatis中动态SQL在mapper.xml中添...

  • MyBatis(四) sql执行流程

    1.MyBatis(三) xml文件解析流程 动态SQL解析,中介绍了MyBatis SQL的解析过程。那么MyB...

  • mybatis问题集合(一)

    一、Mybatis动态sql是做什么的?都有哪些动态sql?简述一下动态sql的执行原理? 以XML 标签的形 式...

  • 2020-04-03Mybatis(2)

    Mybatis日志管理 pom.xml增加依赖 在resources下新增logback.xml文件 动态SQL ...

  • MyBatis 动态SQL(*.xml)

    原文参考MyBatis 动态SQL MyBatis的动态SQL大大减少了拼接SQL语句时候的各种格式问题,这里摘录...

  • 使用Example及Example[Criteria]

    mybatis-generator会为每个字段产生Criterion,为底层的mapper.xml创建动态sql。...

  • mybatis中${}、 #{}区别及应用场景

    动态sql是mybatis的主要特性之一。在mapper中定义的参数传到xml中之后,在查询之前mybatis会对...

  • 动态sql

    根据不同条件,需要执行不同的sql命令 MyBatis中动态sql是在mapper.xml中添加逻辑判断

  • MyBatis核心知识点

    (1)Mybatis动态sql是做什么的?都有哪些动态sql?能简述一下动态sql的执行原理不? Mybatis动...

网友评论

      本文标题:MyBatis 动态SQL(*.xml)

      本文链接:https://www.haomeiwen.com/subject/xvubzftx.html