【MyBatis学习笔记七】——MyBatis动态SQL常用标签

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值