mybatis动态SQL-<if>标签详解

2年前 (2022) 程序员胖胖胖虎阿
317 0 0

<if>标签在mybatis的开发工作中主要用于where查询,insert插入和update更新三种操作中,接下来对每种操作中的<if>标签做详细讲述.

案例使用代码参照<SpringBoot整合MyBatis>.

where查询中使用<if>标签:

通过判断参数值是否为空来决定是否使用某个条件,需要注意的是,此处where 1=1 条件不可省略,可以用<where>标签题换,可读性更高,更佳优雅.

在SysUserMapper.xml中新增<select>标签:

<select id="selectListByCondition" resultMap="sysUserMap" parameterType="Sysuser">
        select <include refid="sysUserSql"/>
        from sys_user
        where 1 = 1
        <if test="id != null">
            and id = #{id}
        </if>
        <if test="userName != null and userName !=''">
            and user_name like concat('%', #{userName}, '%')
        </if>
        <if test="userCode != null and userCode != ''">
            and user_code = #{userCode}
        </if>
        <if test="userInfo != null and userInfo != ''">
            and user_info like concat('%', #{userInfo}, '%')
        </if>
        <if test="status != null and status != ''">
            and status = #{status}
        </if>
    </select>

insert新增中使用<if>标签:

通过判断参数值是否为空来决定是否将SQL字段和对象加入到SQL语句中:

在SysUserMapper.xml中修改<insert>标签:

<insert id="insertSysUser" useGeneratedKeys="true" keyProperty="id">
        <!--insert into sys_user(user_name, user_code, user_info, status) values (#{userName}, #{userCode}, #{userInfo}, #{status})-->
        insert into sys_user (
        <if test="userName != null and userName != ''">
            user_name,
        </if>
        <if test="userCode != null and userCode != ''">
            user_code,
        </if>
        <if test="userInfo != null and userInfo != ''">
            user_info,
        </if>
        status) values (
        <if test="userName != null and userName != ''">
            #{userName},
        </if>
        <if test="userCode != null and userCode != ''">
            #{userCode},
        </if>
        <if test="userInfo != null and userInfo != ''">
            #{userInfo},
        </if>
        #{status}
        )
    </insert>

update修改中使用<if>标签:

通过判断参数值是否为空来决定是否将SQL字段和对象加入到SQL语句中:

在SysUserMapper.xml中修改<update>标签:

<update id="updateSysUser">
        <!--update sys_user set user_name = #{userName}, user_code = #{userCode}, user_info = #{userInfo}, status = #{status} where id = #{id}-->
        update sys_user
        <set>
            <if test="userName != null and userName !=''">
                user_name = #{userName},
            </if>
            <if test="userCode != null and userCode != ''">
                user_code = #{userCode},
            </if>
            <if test="userInfo != null and userInfo != ''">
                user_info = #{userInfo},
            </if>
            <if test="status != null and status != ''">
                status = #{status},
            </if>
            id = #{id} where id = #{id}
        </set>
    </update>

版权声明:程序员胖胖胖虎阿 发表于 2022年9月28日 下午5:08。
转载请注明:mybatis动态SQL-<if>标签详解 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...