动态sql

本文详细介绍了如何在Mybatis中使用动态SQL,包括if、where、choose、foreach等标签,以应对不同业务场景下的SQL变化,提升开发灵活性。通过实例解析了各种动态SQL的用法和注意事项,以及其在实际开发中的重要性。
摘要由CSDN通过智能技术生成

1.if

示例:

<select id="getStudentByAge_if" parameterType="int" resultType="Student">
    select * from tbl_student where 1=1
    <if test="age>0">
        and age=#{age}
    </if>
</select>

注意:对于只有一个参数时,运行后会报mybatis找不到参数的错误:

解决办法:

<1:if标签中test的参数使用_parameter代替:

<2:在接口的方法参数前添加注解:

 

2:where :

示例:

<select id="getStudent_where" parameterType="Student" resultType="Student">
    select * from tbl_student
    <where>
        <if test="name!=null &amp;&amp;name!=''">
            name=#{name}
        </if>
        <if test="score!=null">
            and score=#{score}
        </if>
    </where>
</select>

注意:where一般与if一起使用。

where 语句后开头需要加and 或or,而第一个and/or会被自动删除。

3:choose:

示例:

<select id="getStudent_choose" parameterType="map" resultType="Student">
    select * from tbl_student
    <choose>
        <when test="name!=null &amp;&amp;name!=''">
            where name=#{name}
        </when>
        <when test="score!=null &amp;&amp;score!=''">
            where score=#{score}
        </when>
        <otherwise>
            where 1=1
        </otherwise>
    </choose>
</select>

注意:choose一般与when/otherwise连用。

4:foreach:

示例:

<select id="getStudent_foreach" parameterType="map" resultType="Student">
    select * from tbl_student
    <if test="ages!=null">
        <where>
            age in
            <foreach collection="ages" open="(" separator="," close=")" item="val">
                #{val}
            </foreach>
        </where>
    </if>
</select>

注意:等同于sql语句:select * from tbl_student where age in(18,19,20)

5:trim:

示例:

<select id="getStudent_trim" parameterType="map" resultType="Student">
    select * from tbl_student
    <trim prefix="where" prefixOverrides="and|or">
        <if test="name!=null &amp;&amp; name!=''">
            and name=#{name}
        </if>
    </trim>
</select>

注意:trim+if能够替代where。

6:set:

示例:

<update id="updateStudent" parameterType="Student">
    update tbl_student
    <set>
        <if test="name!=null &amp;&amp; name!=''">
          name=#{name},
        </if>
        <if test="score!=null &amp;&amp; score!=''">
            score=#{score},
        </if>
        <if test="birth!=null &amp;&amp; birth!=''">
            birth=#{birth},
        </if>
        <if test="age!=null &amp;&amp; age!=''">
            age=#{age},
        </if>
    </set>
        where id=#{id}

注意:

sql语句的拼接中,set会自动删除最后一个逗号。

另外,在测试中,修改操作需要commit提交。

总结:1.什么是动态sql?

我认为,动态sql说到底就是在实际业务需求中,为了满足不同的需求,对于不同的sql语句,要执行的不同的操作,而能够随时灵活更改的sql语句。

2.为什么要使用动态sql?

就是为了满足实际开发中,能够根据用户随时更改的业务需求,而灵活地对数据进行增删改操作,尽可能减少对代码的更改,而及时完成要求。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值