Mybatis之动态SQL(choose、when、otherwise)

本文介绍了MyBatis中动态SQL的<choose>、<when>、<otherwise>标签用法,通过示例展示了如何在<where>标签内根据条件拼接SQL查询语句,以及在<update>标签中使用<set>来动态设置更新字段。在测试类中,我们测试了当传入不同参数时,SQL查询和更新语句的动态构建效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上篇以及学习了动态sql的if用法,这里学习choose、when、otherwise的用法。

先介绍<where>标签的用法:

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

这里直接上mapper.xml代码

    <select id="queryBlogChoose" parameterType="map" resultType="com.lizheng.pojo.Blog">
        select * from mybatis.blog
        <where>
            <choose>
                <when test="title != null">
                    and title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>

测试类

    @Test
    public void queryBlogChooseTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("author","狂神说");
        map.put("title","Mybatis");
        mapper.queryBlogChoose(map);
        sqlSession.commit();
        sqlSession.close();
    }

==============================================================================================================

增加set用法

    <update id="queryBlogInsert" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
            <if test="views != null">
                views = #{views},
            </if>
        </set>
        where id = #{id}
    </update>

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值