【Mybatis】动态SQL

前言

动态 SQL 是 MyBatis 的强大特性之一。

如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。

利用动态 SQL,可以彻底摆脱这种痛苦。

1、where if标签

对于查询条件数量不确定的情况,Mybatis使用这两个标签组合可以解决

IF 进行条件判断,如果为真,将IF标签内的内容拼接到SQL语句中

WHERE 进行去掉多余and的工作

需求

现在查询条件不定,有可能是name、album、author 三种任意组合。用Mybatis的动态SQL完美解决

该表对应Mapper如下:

<select id="querySong" parameterType="map" resultType="com.ff.bean.Song">
    select * from song
    <where>
        <if test="name != null">
            name = #{name}
        </if>
        <if test="album != null">
            and album = #{album}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

测试

只传入name
    [DEBUG] 2021-04-10 16:54:22,957 ==>  Preparing: select * from song WHERE name = ?
	[DEBUG] 2021-04-10 16:54:22,988 ==> Parameters: 夜曲(String)
	[DEBUG] 2021-04-10 16:54:23,015 <==      Total: 1
	Song{id=1, name='夜曲', album='十一月的肖邦', author='周杰伦'}
只传入album
    [DEBUG] 2021-04-10 16:55:44,012 ==>  Preparing: select * from song WHERE album = ?
	[DEBUG] 2021-04-10 16:55:44,046 ==> Parameters: 十一月的肖邦(String)
	[DEBUG] 2021-04-10 16:55:44,073 <==      Total: 2
	Song{id=1, name='夜曲', album='十一月的肖邦', author='周杰伦'}
	Song{id=2, name='枫', album='十一月的肖邦', author='周杰伦'}
传入album和author
    [DEBUG] 2021-04-10 17:27:18,338 ==>  Preparing: select * from song WHERE album = ? and author = ?
	[DEBUG] 2021-04-10 17:27:18,389 ==> Parameters: 十一月的肖邦(String), 周杰伦(String)
	[DEBUG] 2021-04-10 17:27:18,429 <==      Total: 2
	Song{id=1, name='夜曲', album='十一月的肖邦', author='周杰伦'}
	Song{id=2, name='枫', album='十一月的肖邦', author='周杰伦'}

2、set if标签

对于更新字段不定的操作,使用这两个标签组合可以完美解决

SET 进行去掉多余 ,的工作

IF 进行判断工作

应用场景

有时修改用户信息,用户可以在密码、性别、年龄等等之间任意组合修改,修改字段不定

<update id="updateUser" parameterType="map">
    update article
    <set>
        <if test="password != null">
            password = #{password},
        </if>
        <if test="sex != null">
            sex = #{sex},
        </if>
        <if test="age != null">
        	age = #{age},
        </if>
    </set>
    where id = #{id}
</update>

3、foreach标签

foreach标签的作用是对集合进行遍历(尤其是在构建 IN 条件语句的时候)

应用场景

当要多选删除的时候,从页面会传来多个id,这些id或组成一个集合

/**
 * 删除
 *
 * @param arr 后台传过来的参数
 */
void deleteArticle(@Param("arr") String[] arr);
<delete id="deleteArticle">
    delete from article where id in
    <foreach collection="arr" item="id" open="(" separator="," close=")">
        #{id}
    </foreach>
</delete>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值