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):
原符号 < <= > >= & ' "
替换符号 < <= > >= & ' "
例如:sql如下:
create_date_time >= #{startTime} and create_date_time <= #{endTime}
第二种写法(2):
大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and create_date_time <![CDATA[ <= ]]> #{endTime}
mybatis常用方法总结的更多相关文章
- tk.mybatis中常用方法的使用(最实用)
一.前言 不知道环境和maven依赖怎么配置的,先看一下这个: SpringBoot整合tk.mybatis 二.方法的介绍和使用 插入方法 int insertSelective(T var1); ...
- Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二
接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...
- 使用mybatis完成通用dao和通用service
使用mybatis完成通用dao和通用service 概述: 使用通用dao和通用service可以减少代码的开发.可以将常用的增删改查放到通用dao中.对不同的or框架,基本上都有自己的实现如Spr ...
- 初识 tk.mybatis.mapper
在博客园发表Mybatis Dynamic Query后,一位园友问我知不知道通用mapper,仔细去找了一下,还真的有啊,比较好的就是abel533写的tk.mybatis.mapper. 本次例子 ...
- MyBatis框架概述
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statement.手动设 ...
- 值得收藏的Mybatis通用Mapper使用大全。
引言 由于小编的记性不太好,每次在写代码的时候总是把通用mapper的方法记错,所以今天把通用mapper的常用方法做一下总结,方便以后直接查看.好了,不废话啦. 引包 <!-- 通用Mappe ...
- Mybatis从认识到了解
目录 MyBatis的介绍 介绍: 为什么选择MyBatis: 与Hibernate的对比: MyBatis的优点: 入门示例 Mybatis核心组件 四大核心组件 SqlSessionFactory ...
- Mybatis JDBC->Mybatis
1 什么是JDBC Java程序都是通过JDBC(Java Data Base Connectivity)连接数据库的,通过SQL对数据库编程.JDBC是由SUN公司(SUN公司已被Oracle公司收 ...
- spring boot开发笔记——mybatis
概述 mybatis框架的优点,就不用多说了,今天这边干货主要讲mybatis的逆向工程,以及springboot的集成技巧,和分页的使用 因为在日常的开发中,当碰到特殊需求之类会手动写一下s ...
随机推荐
- Macbook Pro上安装Windows 7虚机
折腾了大半天,终于搞定. 首先是安装VirtualBox,之后关键的是需要Win7虚机种子,百度了下去系统之家下的. 如果不是Ghost系统的话,VirtualBox可以直接load安装. 但是那边都 ...
- Hibernate 一对一、一对多、多对多注解mappedBy属性的总结
mappedBy: 所填内容必为本类在另一方的字段名. 表示:本类放弃控制关联关系,所有对关联关系的控制,如:建立.解除与另一方的关系,都由对方控制,本类不管.举个例子: Teacher和Studen ...
- Druid.io系列(四):索引过程分析
原文链接: https://blog.csdn.net/njpjsoftdev/article/details/52956083 Druid底层不保存原始数据,而是借鉴了Apache Lucene.A ...
- gil基本介绍
一 引子 定义: In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native t ...
- 转 Quartz将Job持久化所需表的说明
QRTZ_CALENDARS 以 Blob 类型存储 Quartz 的 Calendar 信息 QRTZ_CRON_TRIGGERS 存储 Cron Trigger,包括 Cron表达式和时区信息 ...
- AJAX跨域调用ASP.NET MVC的问题及解决方案
AJAX跨域调用ASP.NET MVC的问题及解决方案 问题描述: 解决方法: 只需要在web.config中添加如下标为红色的内容即可: <system.webServer> <h ...
- Android中RelativeLayout各个属性
android:layout_above="@id/xxx" --将控件置于给定ID控件之上 android:layout_below="@id/xxx" ...
- 「小程序JAVA实战」小程序的flex布局(22)
转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-22/ 之前已经把小程序的框架说完了,接下来说说小程序的组件,在说组件之前,先说说布局吧.源码:ht ...
- 跟我学算法-pca(降维)
pca是一种黑箱子式的降维方式,通过映射,希望投影后的数据尽可能的分散, 因此要保证映射后的方差尽可能大,下一个映射的方向与当前映射方向正交 pca的步骤: 第一步: 首先要对当前数据(去均值)求协方 ...
- Kibana安装(图文详解)(多节点的ELK集群安装在一个节点就好)
对于Kibana ,我们知道,是Elasticsearch/Logstash/Kibana的必不可少成员. 前提: Elasticsearch-2.4.3的下载(图文详解) Elasticsearch ...