Mybatis中动态Sql的if、for和foreach使用

动态sql片段使用方法:创建sql标签在标签体中输入动态代码段,其中id最好为能表示这个代码段信息的,然后再需要引用的地方用include标签引用,include中的id为被引用的sql代码段id。下面是动态语法的使用。

    //where使用接口中定义的方法
    List<Student> SelAll2(Student student);

where和if联合使用,当if中test条件成立时,才会将标签体的内容拼接在SQL语句中

<!--    where-->
    <select id="SelAll2" resultType="org.example.Entity.Student">
        select id,name,email,age from student
        <where>
            <if test="email !=null and email !=''">
                email=#{email}
            </if>
            <if test="age!=0">
                and age>#{age}
            </if>
        </where>
    </select>
    //foreach用法1
    List<Student> SelAll3(List<Integer> id);
    //foreach用法2
    List<Student> SelAll4(List<Student> students);

也可以不用foreach中的open和close,只要能拼接成一个正确的SQL语句即可

<!--    where  collection为方法的类型 数组为array  list集合则为list
        item  自定义的,表示数组和集合成员的变量
        open  循环开始时的字符
        close 循环结束时的字符
        separator 集合成员中的分隔符
        第一种用法
-->
    <select id="SelAll3" resultType="org.example.Entity.Student">
         select id,name,email,age from student where id in
         <foreach collection="list" item="list" open="(" close=")" separator=",">
            #{list}
         </foreach>
    </select>
<!--    第二种用法-->
    <select id="SelAll4" resultType="org.example.Entity.Student">
        select id,name,email,age from student where id in
        <foreach collection="list" item="list" open="(" close=")" separator=",">
        #{list.id}
            <if test="list.name !=''">
                and name!=#{list.name}
            </if>
        </foreach>
    </select>
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

syf_wfl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值