mybatis动态SQL

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)

提取共性

使用sql标签可以提取sql的共性, 然后使用include 标签引入sql标签的id

例如:

<!-- 通过sql标签提取sql中的共性 -->
<sql id="queryWhereId">
    from sys_logs
    <if test="username != null and username != ''">
        <where>
            username like concat("%", #{username}, "%")
        </where>
    </if>
</sql>

<!-- 查询当前页面记录总数 -->
<select id="findPageObjects" resultType="com.cy.pj.sys.pojo.SysLog">
    select * 
    <!-- 包含id为queryWhereId的sql元素 -->
    <include refid="queryWhereId"/>
    order by createdTime desc 
    limit #{startIndex}, #{pageSize}
</select>

<!-- 按条件查询总记录数 -->
<select id="getRowCount" resultType="int">
    select count(*)
    <!-- 包含id为queryWhereId的sql元素 -->
    <include refid="queryWhereId"/>
</select>
原文地址:https://www.cnblogs.com/zpKang/p/13176255.html