当前位置:Gxlcms > 数据库问题 > mybatis动态sql

mybatis动态sql

时间:2021-07-01 10:21:17 帮助过:21人阅读

id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>

 

  • choose when otherwise 多选一,相当于if else 
  • <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>

      3.trim where set 智能得插入 where and set ,等关键字,注意where与and配合使用,而set与,配合使用

    <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>
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
      ... 
    </trim>
    <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>
    <trim prefix="SET" suffixOverrides=",">
      ...
    </trim>

      4.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动态sql

    标签:拼接   语句   update   type   author   color   style   err   ati   

    人气教程排行