【mybatis】动态SQL

目录

动态SQL

1、if标签

2、where标签

3、foreach标签


动态SQL

mybatis动态SQL,采用的基于OGNL表达式来操作的。根据表达式的不同进行动态的SQL的拼接、组装

动态SQL标签:if、where、trim标签(where、set)、foreach

1、if标签

if表达式一般使用在SQL的where条件后面,判断参数是否传递使用if test属性,该属性必填,为true或false,test使用的OGNL表达式处理,返回true则进入到if标签中的SQL,返回false则不会进入标签

<select id="selectStudent" parameterType="student" resultMap="StudentMap">
        select * from Student where 1=1
        <if test="SID != null and SID != 0">
            and SID = #{SID}
        </if>
        <if test="Sage != null">
            and Sage = #{Sage}
        </if>
    </select>

if表达式根据条件包含为where的一部分,常使用与查询,insert操作,update操作

执行情况:

  • SID和Sage都传递:select * from Student where 1=1 and SID = ? and Sage = ?
  • SID传递:select * from Student where 1=1 and SID = ?
  • Sage传递:select * from Student where 1=1 and Sage = ?
  • 不传递参数:select * from Student where 1=1

2、where标签

where标签作用:如果该标签包含的元素有返回值,就插入一个where,如果where后面的字符串是以and或者or开头的,则将他们提出

<select id="selectStudent" parameterType="student" resultMap="StudentMap">
        select * from Student
        <where>
            <if test="SID != null and SID != 0">
                and SID = #{SID}
            </if>
            <if test="Sage != null">
                and Sage = #{Sage}
            </if>
        </where>
    </select>

执行情况:

  • SID和Sage都传递:select * from Student where SID = ? and Sage = ?
  • SID传递:select * from Student where SID = ?
  • Sage传递:select * from Student where Sage = ?
  • 不传递参数:select * from Student

where表达式一般和if表达式一块使用,如果条件一个都不满足,则不拼接where条件,如果有一个或者多个if表达式,where会直接拼接在SQL上,并且紧随where的表达式的and或者or会被忽略掉

3、foreach标签

需要根据SID批量的查询Student信息,select * from Student where SID in (1,2,3,4,5);

 <select id="selectStudentByIds"  resultMap="StudentMap">
        select * from Student where SID in
        <foreach collection="list"  item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

标签属性解释:

<foreach表达式>

  • collection属性:必填,指定的入参的类型;列表:list,数组:array,hashmap:map;
  • item属性:起名字,给集合中单个元素起名称
  • open属性:开始的字符串
  • close属性:结束的字符串
  • separator属性:数据之间的分隔符

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值