当前位置:   article > 正文

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

mybatis if

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

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

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

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

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

  1. <select id="selectListByCondition" resultMap="sysUserMap" parameterType="Sysuser">
  2. select <include refid="sysUserSql"/>
  3. from sys_user
  4. where 1 = 1
  5. <if test="id != null">
  6. and id = #{id}
  7. </if>
  8. <if test="userName != null and userName !=''">
  9. and user_name like concat('%', #{userName}, '%')
  10. </if>
  11. <if test="userCode != null and userCode != ''">
  12. and user_code = #{userCode}
  13. </if>
  14. <if test="userInfo != null and userInfo != ''">
  15. and user_info like concat('%', #{userInfo}, '%')
  16. </if>
  17. <if test="status != null and status != ''">
  18. and status = #{status}
  19. </if>
  20. </select>

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

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

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

  1. <insert id="insertSysUser" useGeneratedKeys="true" keyProperty="id">
  2. <!--insert into sys_user(user_name, user_code, user_info, status) values (#{userName}, #{userCode}, #{userInfo}, #{status})-->
  3. insert into sys_user (
  4. <if test="userName != null and userName != ''">
  5. user_name,
  6. </if>
  7. <if test="userCode != null and userCode != ''">
  8. user_code,
  9. </if>
  10. <if test="userInfo != null and userInfo != ''">
  11. user_info,
  12. </if>
  13. status) values (
  14. <if test="userName != null and userName != ''">
  15. #{userName},
  16. </if>
  17. <if test="userCode != null and userCode != ''">
  18. #{userCode},
  19. </if>
  20. <if test="userInfo != null and userInfo != ''">
  21. #{userInfo},
  22. </if>
  23. #{status}
  24. )
  25. </insert>

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

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

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

  1. <update id="updateSysUser">
  2. <!--update sys_user set user_name = #{userName}, user_code = #{userCode}, user_info = #{userInfo}, status = #{status} where id = #{id}-->
  3. update sys_user
  4. <set>
  5. <if test="userName != null and userName !=''">
  6. user_name = #{userName},
  7. </if>
  8. <if test="userCode != null and userCode != ''">
  9. user_code = #{userCode},
  10. </if>
  11. <if test="userInfo != null and userInfo != ''">
  12. user_info = #{userInfo},
  13. </if>
  14. <if test="status != null and status != ''">
  15. status = #{status},
  16. </if>
  17. id = #{id} where id = #{id}
  18. </set>
  19. </update>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/255725?site
推荐阅读
相关标签
  

闽ICP备14008679号