• 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}

  

mybatis常用方法总结的更多相关文章

  1. tk.mybatis中常用方法的使用(最实用)

    一.前言 不知道环境和maven依赖怎么配置的,先看一下这个: SpringBoot整合tk.mybatis 二.方法的介绍和使用 插入方法 int insertSelective(T var1); ...

  2. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二

    接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...

  3. 使用mybatis完成通用dao和通用service

    使用mybatis完成通用dao和通用service 概述: 使用通用dao和通用service可以减少代码的开发.可以将常用的增删改查放到通用dao中.对不同的or框架,基本上都有自己的实现如Spr ...

  4. 初识 tk.mybatis.mapper

    在博客园发表Mybatis Dynamic Query后,一位园友问我知不知道通用mapper,仔细去找了一下,还真的有啊,比较好的就是abel533写的tk.mybatis.mapper. 本次例子 ...

  5. MyBatis框架概述

    MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statement.手动设 ...

  6. 值得收藏的Mybatis通用Mapper使用大全。

    引言 由于小编的记性不太好,每次在写代码的时候总是把通用mapper的方法记错,所以今天把通用mapper的常用方法做一下总结,方便以后直接查看.好了,不废话啦. 引包 <!-- 通用Mappe ...

  7. Mybatis从认识到了解

    目录 MyBatis的介绍 介绍: 为什么选择MyBatis: 与Hibernate的对比: MyBatis的优点: 入门示例 Mybatis核心组件 四大核心组件 SqlSessionFactory ...

  8. Mybatis JDBC->Mybatis

    1 什么是JDBC Java程序都是通过JDBC(Java Data Base Connectivity)连接数据库的,通过SQL对数据库编程.JDBC是由SUN公司(SUN公司已被Oracle公司收 ...

  9. spring boot开发笔记——mybatis

    概述   mybatis框架的优点,就不用多说了,今天这边干货主要讲mybatis的逆向工程,以及springboot的集成技巧,和分页的使用   因为在日常的开发中,当碰到特殊需求之类会手动写一下s ...

随机推荐

  1. Ten Qualities of an Effective Team Player

    If you were choosing team members for a business team in your organization, who would the best team ...

  2. Java-Runoob-高级教程:Java 实例

    ylbtech-Java-Runoob-高级教程:Java 实例 1.返回顶部 1. Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. ...

  3. 016:Explain

    一. Explain EXPLAIN 官方文档 1.explain说明 explain是解释SQL语句的执行计划,即显示该SQL语句怎么执行的 使用explain的时候,也可以使用desc 5.6 版 ...

  4. 由 MySQL server 和 mysql-connector 版本的不匹配引发的一场惊魂

    剧情还原 今天原计划给领导演示一个小Demo, 昨天在自己机器上调通OK以后就下班了... 今天上午早会后,领导说 “昨天,我让我们IT同事把新的测试环境搭建好了,XXX 你把要演示的Demo部署到上 ...

  5. hotplug_uevent机制_修改mdev配置支持U盘自动挂载学习笔记

    1.接入U盘,看输出打印信息并分析 (1)输出信息 自动创建设备节点 (2)用ls命令查看 这里/dev/sda表示整个U盘,/dev/sda1表示这个U盘的第一个分区. (3)手动挂载,查看文件,手 ...

  6. 【BZOJ】1001: [BeiJing2006]狼抓兔子(最小割 / 对偶图)

    题目 传送门:QWQ 分析 显然答案是最小割. 然后dinic卡一卡过去了. 其实是懒得写转对偶图:正解 (dinic原来写的是vector,后来改的比较鬼畜 代码 #include <bits ...

  7. oracle 索引使用小结

    1. 普通索引 create index my_index on test (col_1); 可创建合并两列或多列的索引,最多可将32列合并在一个索引中(位图索引最多可合并30列) create in ...

  8. CocoStudio创建动画帧

    进入动画编辑器 选择“形体模式” 右键点击资源窗口的资源,可以进行删除,重命名的操作:  可以再资源窗口下方的预览窗口,查看选中的资源预览效果图: 右键点击“对象结构”,创建图层 选择“动画模式” 右 ...

  9. C#命名规则和风格(收集)

    1.     文件命名组织 1-1文件命名 1.        文件名遵从Pascal命名法,无特殊情况,扩展名小写. 2.        使用统一而又通用的文件扩展名: C# 类 .cs 1-2文件 ...

  10. oracle查看登录到oracle服务器的客户端ip

    1. 在sys模式下创建一个表,用于记录客户端登录数据库服务器的详细信息. 1 create table login_history 2 ( 3 username varchar2(60), --用户 ...