zoukankan      html  css  js  c++  java
  • mybatis常用方法总结

    • mybatis的强大特性之一就是动态SQL。我们在写复杂查询的时候,会发现复杂查询包括了各种各样的判断,我们很难一鼓作气的写出完美的查询。动态SQL语句可以帮助我们拼接不同的SQL语句,而已让我们的代码变得更加优雅且功能更加强大。这一篇给大家介绍一下if的用法

      下边就是现在MyBatis的动态SQL在XML中支持的几种标签,他们分别是:

      • if
      • choose
      • trim(where、set)
      • foreach
      • bind

        if用法

      if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段,还可以在INSERT语句中用来判断是否插入某个字段的值

      where:(我们的项目中模糊查询很多都用到了if,如果模糊条件不为空,则执行模糊查询,如果为空就到此为止)

      <select id="FuzzyQueryClassByStrlike" parameterType="java.lang.String" resultType="com.dmsdbj.itoo.basicInfo.entity.ext.DivideClassModel">
              select
                  tc.id as classId,
                  tc.class_code as classCode,
                  tc.class_name as className,
                  tc.profession_id as professionId,
                  p.major_name as professionName,
                  p.institution_id as InsititutionId,
                  i.institution_name as InsititutionName
              from t_class tc
              inner join  t_profession p on tc.profession_id = p.id
              inner join t_institution i on p.institution_id=i.id
              <if test="strLike !='' and strLike !=null">
                  WHERE(
                  tc.class_code LIKE concat('%',#{strLike},'%')
                  OR
                  tc.class_name LIKE concat('%',#{strLike},'%')
                  OR
                  p.major_name LIKE concat('%',#{strLike},'%')
                  OR
                  i.institution_name LIKE concat('%',#{strLike},'%')
                  )
              </if>
      

        update(insert同理):如果要更新很多字段,但是一个步骤就可以完成,我们就可以使用if来进行判断,如果这个参数不为空则更新

      <update id="updateById" parameterType="com.dmsdbj.itoo.basicInfo.entity.EducationExperienceEntity">
              update t_education_experience
              <set>
                  <if test="remark != null">
                      remark = #{remark,jdbcType=VARCHAR},
                  </if>
                  <if test="operator != null">
                      operator = #{operator,jdbcType=VARCHAR},
                  </if>
                  <if test="endDate != null">
                      end_date = #{endDate,jdbcType=DATE},
                  </if>
                  <if test="schoolName != null">
                      school_name = #{schoolName,jdbcType=VARCHAR},
                  </if>
                  <if test="startDate != null">
                      start_date = #{startDate,jdbcType=DATE},
                  </if>
                  <if test="teacherName != null">
                      teacher_name = #{teacherName,jdbcType=VARCHAR},
                  </if>
                  <if test="studentId != null">
                      student_id = #{studentId,jdbcType=VARCHAR},
                  </if>
                  <if test="isDelete != null">
                      is_delete = #{isDelete,jdbcType=TINYINT},
                  </if>
                  <if test="education != null">
                      education = #{education,jdbcType=VARCHAR},
                  </if>
                  <if test="createTime != null">
                      create_time = #{createTime,jdbcType=TIMESTAMP},
                  </if>
                  <if test="updateTime != null">
                      update_time = #{updateTime,jdbcType=TIMESTAMP},
                  </if>
              </set>
              where id = #{id,jdbcType=VARCHAR} and is_delete = 0
        </update>  
      

        注意:
      if标签中有一个test属性,test属性值是一个符合OGNL要求的判断表达式,表达式的结果可以使true或者false,除此之外所有的非0值都为true。

    上一篇中我们讲解了if标签的使用,但是他无法实现if…else的逻辑判断,这就要用到我们这一篇提到的choose when otherwise标签。

    使用规则:

    一个choose中至少有一个when,有0个或一个otherwise

    举个例子:

    <select id="selectByIdOrUserName" resultType="cd.mybatis.model.SysUser">
    select id,
        user_name userName,
        user_password UserPassword,
        user_info userInfo
    from sys_user
    where 1=1
    <choose>
        <when test="id!=null">
           and id=#{id}
        </when>
        <when test="userName !=null and userName !='' ">
           and user_name =#{uerName}
        </when>
        <otherwise>
           and 1=2
        </otherwise> 
    </choose>
    </select>
    

      

    代码解释:

    查询用户的信息,如果提供了id,那么优先使用id查询,如果没有id,提供了username,那么使用username作为条件查询,如果都没有则执行otherwise,确保返回值的正确

    上一篇博客我们简单的介绍了一下choose when otherwise的用法,这一篇我们来聊聊另外当个差不多的标签的用法:where、set、trim

    1. where标签的作用:如果该标签包含的元素中有返回值,就插入一个where;如果where后面的字符是以AND和OR开头的,就讲他们剔除

     举个例子:

    <select id="selectByUser" resultType="cd.mybatis.simple.model.SysUser">
            select id,
            user_name userName,
            user_password userPassWord,
            user_email userEmail,
            user_info userInfo,
            user_img headImg,
            create_time createTime
        from sys_user
        where 1=1
            <if test="userName != null and userName !=''">
                and user_name like concat('%',#{userName},'%')
            </if>
            <if test="userEmail !=''and userEmail !=null">
                and user_email=#{userEmail}
            </if>
        </select>
    

      使用where标签修改后:

    <select id="selectByUser" resultType="tk.mybatis.simple.model.SysUser">
            select id,
            user_name userName,
            user_password userPassWord,
            user_email userEmail,
            user_info userInfo,
            user_img headImg,
            create_time createTime
        from sys_user
        <where>
            <if test="userName != null and userName !=''">
                and user_name like concat('%',#{userName},'%')
            </if>
            <if test="userEmail !=''and userEmail !=null">
                and user_email=#{userEmail}
            </if>
        </where>
        </select>
    

      

    第一个例子中,如果没有where1=1,当两个if条件都不满足时,最后生成的SQL就会以where结束,这样不符合SQL规范,所以需要加一个默认为true的条件

    第二个例子,如果两个if条件不满足的时候,where标签包着的这一段代码就会被剔除掉,在SQL中就不会出现这一段代码了。

    2.set标签的作用:如果该标签包含的元素中有返回值,就插入一个set;如果set后面的字符串是以逗号结尾的,就将这个逗号剔除

     举个例子:

    <!--批量更新学生信息-XX-2017-7-24 17:00:08-->
        <update id="updateStudentList">
            <foreach collection="studentEntitys" item="item" index="index" open="" close="" separator=";">
                update t_student
                <set>
                    <if test="item.classesId!='' and item.classesId!=null">
                        classes_id=${item.classesId}
                    </if>
                    <if test="item.code!='' and item.code!=null">
                        code=${item.code}
                    </if>
                    <if test="item.roomId!='' and item.roomId!=null">
                        room_id=${item.roomId}
                    </if>
                </set>
                where id = ${item.id}
            </foreach>
        </update>
    

      

    注意最后的where id=${item.id} 是不可省略的,如果set包含的内容为空,只能避免最后遗留的逗号问题

    3.trim用法:where和set标签的功能都可以使用trim标签来实现,并且在底层就是通过TrimSqlNode实现的

    where标签对应的trim实现:

    <trim prefix="WHERE" prefixOverrides="AND |OR ">
    ...
    </trim>
    

      set标签对应的trim实现:

    <trim prefix="SET" prefixOverrides=",">
    ...
    </trim>
    

      

    trim属性

    • prefix:当trim元素内包含内容时,会给内容增加prefix指定前缀
    • prefixOverrides: 当trim元素内包含内容时,会把内容中匹配的前缀字符串去掉
    • suffix: 当trim元素内包含内容时,会给内容增加suffix指定的后缀
    • suffixOverrides:当trim内包含内容时,会把内容中匹配的后缀字符串去掉。

     

     

    mybatis中大于等于小于等于的写法

    第一种写法(1):
    
    原符号       <        <=      >       >=       &        '        "
    替换符号    &lt;    &lt;=   &gt;    &gt;=   &amp;   &apos;  &quot;
    例如:sql如下:
    create_date_time &gt;= #{startTime} and  create_date_time &lt;= #{endTime}
    
    第二种写法(2):
    大于等于
    <![CDATA[ >= ]]>
    小于等于
    <![CDATA[ <= ]]>
    例如:sql如下:
    create_date_time <![CDATA[ >= ]]> #{startTime} and  create_date_time <![CDATA[ <= ]]> #{endTime}

      

  • 相关阅读:
    thinkphp简洁、美观、靠谱的分页类
    查询文章的上下篇Sql语句
    人类阅读的优越方式打印php数组
    弹出遮罩层后,如何禁止底层页面的滚动
    解决PHP Redis扩展无法加载的问题(zend_new_interned_string in Unknown on line 0)
    PHP Warning: PHP Startup: redis: Unable to initialize module Windows版本phpredis扩展
    带你使用JS-SDK自定义微信分享效果
    lnmp环境切换php版本,并安装相应redis扩展
    最新git源码下载地址
    微信小程序之发送模板消息(通过openid推送消息给用户)
  • 原文地址:https://www.cnblogs.com/wlsblog/p/7699420.html
Copyright © 2011-2022 走看看