记录mybatis动态sql

(注:本文参考自刘增辉老师的《MyBatis从入门到精通》)

目录

1.1 if 用法

1.1.1 在 where 条件中使用 if

1.1.2 在 update 更新列中使用 if

1.1.3 在 insert 动态插入列中使用 if

2.1 choose 用法 

3.1 where set trim 用法

3.1.1 where 用法

3.1.2 set 用法

3.1.3 trim 用法

4.1 foreach 用法

4.1.1 foreach 实现 in 集合

4.1.2 foreach 实现批量插入

4.1.3 foreach 实现动态 update (以参数类型Map为例)

5.1 bind 用法


1.1 if 用法

if 标签通常用于where语句中,通过判断参数值来决定是否使用某个查询条件,它也常用于update语句中判断是否更新某个字段,还可以在INSERT语句中用来判断是否插入某个字段的值。
字符串的判断几乎都包含null和空的判断,这两个条件不是必须写在一起的,可以根据实际业务决定是否需要进行空值判断。

1.1.1 在 where 条件中使用 if

假如有这么一个需求:客户输入名字,则根据名字进行查询,否则,做全表查询。这时候我们就可以在 where 条件中使用 if。

例如,在 AnimalMapper.xml中添加如下sql: 

    <select id="getAnimalByName" resultType="com.zhang.entity.Animal">
        select * from animal
        <where>
            <if test="name != null and name != ''">
                and `name` = #{name}
            </if>
        </where>
    </select>

1.1.2 在 update 更新列中使用 if

现在要实现这样一个需求:只更新有变化的字段。需要注意,更新的时候不能将原来有值(没有发生变化的字段)更新为空或null。通过 if 标签可以实现这种动态列更新。

例如,在 AnimalMapper.xml中添加如下sql: 

    <update id="update">
        update animal
        <set>
            <if test="age != null and age != ''">
                `age` = #{age},
            </if>
            <if test="name != null and name != ''">
                `name` = #{name},
            </if>
            <if test="hobby != null and hobby != ''">
                `hobby` = #{hobby},
            </if>
        </set>
        where `id` = #{id}
    </update>

1.1.3 在 insert 动态插入列中使用 if

在数据库表中插入数据的时候,如果某列的参数值不为空,就使用传入的值,如果传入参数为空,就使用数据库中的默认值(通常是空),而不使用传入的空值使用 if 就可以这种动态插入列的功能。

例如,在 AnimalMapper.xml中添加如下sql: 

 <insert id="addOne" parameterType="com.zhang.entity.Animal">
        insert into `animal`
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null and id != ''">
                `id`,
            </if>
            <if test="name != null and name != ''">
                `name`,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null and id != ''">
                #{id,jdbcType=VARCHAR},
            </if>
            <if test="name != null and name != ''">
                #{name,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

2.1 choose 用法 

if 标签提供了基本的条件判断,但是它无法实现if...else-if...else...的逻辑,要想实现这样的逻辑,就需要用到choose when otherwise标签。choose元素中包含when和otherwise两个标签,一个choose中至少有一个when,有0个或者1个otherwise。

在已有的`animal`表中,除了主键id外&#x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值