Mybatis-SQL

什么是动态SQL:
根据不同的条件生成不同的SQL语句

    if
    choose (when, otherwise)
    trim (where, set)
    foreach

搭建环境:

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

IF

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select *from mybatis1.blog where 1=1
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>

choose (when, otherwise)

 <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select *from mybatis1.blog
        <where>
          <choose>
              <when test="title!=null">
                  title=#{title}
              </when>
              <when test="author!=null">
               and  author=#{author}
              </when>
            <otherwise>
                and views=#{views}
            </otherwise>
          </choose>
        </where>
    </select>

trim (where, set)

 <select id="queryBlogIF" parameterType="map" resultType="blog">
        select *from mybatis1.blog
        <where>
         <if test="title!=null">
             title=#{title}
        </if>
         <if test="author!=null">
                and author=#{author}
         </if></where>
    </select>
 <update id="upDataBlog" parameterType="map">
        update mybatis1.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
               author=#{author},
            </if>
        </set>
        where id=#{id}
    </update>

foreach

posted @ 2022-04-20 14:53  离地一厘米的飞翔  阅读(73)  评论(0)    收藏  举报