首页 > 数据库技术 > 详细

mybatis动态SQL

时间:2020-06-22 13:07:07      阅读:72      评论:0      收藏:0      [点我收藏+]

mybatis动态SQL

动态sql可以增加sql的灵活性, 也是mybatis最大的优势功能 (更多标签可查看官方文档)

if 和 where标签

格式:

<if test="判定条件">
    sql语句
</if>

例如: 查询指定工资范围的员工信息

<select id="findBySal12" resultType="com.tedu.pojo.Emp">
    select * from emp 
    where 1 = 1
    <if test="minsal != null">
        and salary &gt;= #{minSal}
    </if>
    <if test="maxSal != null">
        and salary &lt;= #{maxSal}
    </if>
</select>

使用1 = 1 是为了防止两个if判断都不生效, 防止sql出现错误

当然也可以使用这种方式: 使用<where> 标签来替换where

select * from emp 
<where>
    <if test="minsal != null">
        and salary &gt;= #{minSal}
    </if>
    <if test="maxSal != null">
        and salary &lt;= #{maxSal}
    </if>
</where>

foreach标签

格式:

<foreach collection="类型" open="开始标志" item="每个元素名字" separator="分隔符" close="结尾标志">
    #{每个元素名字}
</foreach>

例如: 根据员工的id批量删除员工信息传过来的参数是一个Ingeger[] ids的数组Integer ids = {1, 3, 5, 7}

<delete id="deleteByIds">
    delete from emp where id in
    <foreach collection="array" open="(" item="id" separator="," close=")">
        #{id}
    </foreach>
</delete>

执行后这个sql就是:

delete from emp where id in (1, 3, 5, 7)

mybatis动态SQL

原文:https://www.cnblogs.com/zpKang/p/13176255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!