优秀的编程知识分享平台

网站首页 > 技术文章 正文

「MyBatis学习笔记七」——MyBatis动态SQL常用标签

nanyue 2024-07-31 12:02:12 技术文章 14 ℃

1.if 标签

  • if 标签,符合标签即执行,用于动态查询语句,类型Java 中的 if 语句
<select id="getAllByIf" resultType="com.demo.entity.User" parameterType="map">
    select * from mybatis.user
    <!--where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。-->
    <where>
    	<if test="username != null">
        	username = #{username}
        </if>
        <if test="password != null">
        	and password = #{password}
        </if>
    </where>
</select>

2.choose、when、otherwise 标签

  • 不想使用所有的条件,而只是想从多个条件中选择一个使用,有点像 Java 中的 switch 语句。
     <select id="getAllByChoose" resultType="com.demo.entity.User" parameterType="map">
        select * from mybatis.user where 1=1
        <choose>
            <when test="username != null">
                and username = #{username}
            </when>
            <when test="password != null">
                and password = #{password}
            </when>
            <otherwise>
                and 1 = 1
            </otherwise>
        </choose>
    </select>

3.set 标签

  • 用于动态更新语句的类似解决方案叫做 set。set可以用于动态包含需要更新的列,忽略其它不更新的列。
  • set会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
    <update id="updateBySet" parameterType="map">
        update mybatis.user
        <set>
            <if test="username != null"> username = #{username},</if>
            <if test="password != null"> password = #{password},</if>
        </set>
        where id = #{id}
    </update>

4.foreach 标签

  • 常用于批量查询,类型Java 中的 foreach 语句
  • 以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
    <select id="getAllByFor" resultType="com.demo.entity.User" parameterType="int">
        select * from mybatis.user where id in
        <foreach collection="list" item="id" index="index" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>
最近发表
标签列表