mybatis动态sql

本文探讨了如何利用MyBatis的动态SQL特性简化JDBC的SQL拼接,包括update、delete、select操作的示例,并介绍了选择、switch-like的choose标签在灵活查询条件中的应用。
摘要由CSDN通过智能技术生成

       动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦

以下是一些动态sql的crud的一些代码呈现

  <update id="update">
        update student
        <trim prefix="set" suffixOverrides=",">

            <if test="stuName!=null">
                stu_name = #{stuName},
            </if>
            <if test="stuName!=null">
                stu_age = #{stuAge},
            </if>
            <if test="stuName!=null">
                stu_sex = #{stuSex}
            </if>
        </trim>
        where stu_no=#{stuNo}

    </update>

 删除更多的sql代码块

 <!--collection:指定输入对象中的集合属性
    item:每次遍历生成的对象
    open:开始遍历时的拼接字符串
    close:结束时拼接的字符串
    separator:遍历对象之间需要拼接的字符串-->
    <delete id="deleteMore">
        delete from student where stu_no in
        <foreach collection="ids" open="(" item="id" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <select id="selectAll" resultType="student">
        select *
        from student
    </select>
  <!--    prefix:前缀
    prefixOverrides:去掉第一个and或者是or 
    -->
    <select id="search" resultType="Student">
        select * from student
        <trim prefix="where" prefixOverrides="and">

            <if test="stuNo != null">
                stu_no = #{stuNo}
            </if>
            <if test="stuName != null">
                and stu_name = #{stuName}
            </if>
            <if test="stuSex != null">
                and stu_sex = #{stuSex}
            </if>
        </trim>
    </select>

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

<select id="search01" resultType="student">
        select *from student
        <where>
            <choose>
                <when test="stuNo!=null">
                    stu_no = #{stuNo}
                </when>
                <when test="stuName!=null">
                    and stu_name = #{stuName}
                </when>
                <otherwise>
                    and stu_sex = #{stuSex}
                </otherwise>
            </choose>
        </where>
    </select>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值