Mybatis动态SQL语句

Mybatis动态SQL语句

动态SQL SQL的内容是变化的 可以根据不同的条件获取到不同的SQL语句

1.if 判断条件

语法结构:

<select id="selectStudentsif" resultType="com.one.domain.Student">
        select id,name,email,age from student where 1='1'
        <if test=" name!=null and name!=''">
            and name = #{name}
        </if>
        <if test=" age >0 ">
            and age=#{age}
        </if>
    </select>
加入if 标签可以进行判断 当满足test条件才能拼接到SQL语句中 但是要注意 如果if的条件一个没成立的话你的SQL语句中就只有一个where没有判断条件 是不合法的 所以需要添加一个恒等式 保证where能运行

2.where 内部可以包含多个if 当多个if同时成立时候 where会自动添加

​ where会自动去掉多余的and 或者 or

 <select id="selectStudentswhere" resultType="com.one.domain.Student">
        select id,name,email,age from student
        <where>
            <if test=" name!=null and name!=''">
                and name = #{name}
            </if>
            <if test=" age >0 ">
                and age=#{age}
            </if>
        </where>
    </select>
将SQL语句中的where变成标签
 但是作用没变化甚至优化了SQL当你if都不成立那么where就不会加入到SQL语句当中

3.foreach 循环java中的数据 list集合 主要用于SQL的in语句中

 <select id="selectStudentsForeach" resultType="com.one.domain.Student">
    select id,name,email,age from student where id in
 <foreach collection="list" item="myid" open="(" close=")" separator=",">
            #{myid}
        </foreach>
    </select>

​ collection:表示接口中的方法参数的类型 如果是数组使用array 如果是list集合就用list
​ item:自定义的 表示数组和集合成员的变量
​ open:循环开始的字符
​ close:循环结束时的字符
​ separator:集合成员之间的分隔符

4.代码片段 就是一些复用的语法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值