mybatis的mapper特殊字符转移以及动态SQL条件查询
前言
我们知道在项目开发中之前使用数据库查询,都是基于jdbc,进行连接查询,然后是高级一点jdbcTemplate进行查询,但是我们发现还是不是很方便,有大量重复sql语句,与代码偶合,效率低下,于是就衍生出来ORM框架,如Mybatis,Hibernate,还有SpringBoot的,Spring Data JPA
条件查询
我们知道在mybatis mapper文件中条件查询符,如>=,<,之类是不能直接写的会报错的需要转移一下 如下图表

详细内容参考
常见的条件查询操作有

我们通过mybatis 提供的特有标签进行条件判断,达到动态拼接sql语句
if标签 where标签 choose when otherwise标签 foreach标签
快速入门
if标签
语法:
<if test="xxx != null and xxx != ''">
test中写判断条件 参数直接paramN或者别名 多个条件使用and或者or连接
只要条件成立就拼接在Sql语句中,都成立就全部都拼接
注意where子句中加上1=1来规避and的风险
如下例子:
<select id="selg" resultType="log">
select * from log where 1=1
<if test="param1!=null and param1!=''">
and outno=#{param1}
</if>
<if test="param2!=null and param2!=''">
and inno=#{param2}
</if>
</select>
where标签
对上面if标签条件判断where连接做了处理会自动的给Sql语句添加where关键字,并将第一个and去除
上面sql可以改造成如下:
<select id="selg" resultType="log">
select * from log
<where>
<if test="param1!=null and param1!=''">
and outno=#{param1}
</if>
<if test="param2!=null and param2!=''">
and inno=#{param2}
</if>
</where>
</select>
choose when otherwise标签
类似于Java语法中的,case,switch语句判断
条件只要有一个成立,其他的就不会再判断了。如果没有成立的条件则默认执行otherwise中的内容
上面sql可以改造成如下:
<select id="selg" resultType="log">
select * from log
<where>
<choose>
<when test="param1!=null and param1!=''">
and outno=#{param1}
</when>
<when test="param2!=null and param2!=''">
and inno=#{param2}
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>
foreach标签
语法:
<foreach collection="idList" item="id" open="(" separator="," close=")">
</foreach>
- collection:要遍历的集合对象
- item:记录每次遍历的结果
- open:在结果的左边添加内容
- separator:结果和结果之间的内容
- close:在最后添加的内容
常用于in查询,和批量插入操作 如下案例:
<select id="selF" parameterType="list" resultType="account">
select * from account where ano in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<insert id="insertBatch">
INSERT INTO t_user
(id, name, password)
VALUES
<foreach collection ="userList" item="user" separator =",">
(#{user.id}, #{user.name}, #{user.password})
</foreach >
</insert>
其他标签使用参考点击进入·
场景案例
- 当我们需要对多张表的关联数据进行复杂动态条件查询的时候,就需要用到
if标签进行判断 如下
根据用户手机号姓名年龄性别,等进行动态条件检索,这个时候我们需要动态通过调节去拼接sql 当条件满足sql语句加上对应条件差许
<select id="findUsersByUser" resultType="cn.soboys.kmall.sys.entity.User">
select tu.USER_ID,tu.USERNAME,tu.SSEX,td.DEPT_NAME,tu.MOBILE,tu.EMAIL,tu.STATUS,tu.CREATE_TIME,
td.DEPT_ID
from t_user tu left join t_dept td on tu.DEPT_ID = td.DEPT_ID
where tu.ADMIN_TYPE_ID >= 0 AND tu.ADMIN_TYPE_ID <= #{userParams.adminType}
<if test="userParams.roleId != null and userParams.roleId != ''">
and (select group_concat(ur.ROLE_ID)
from t_user u
right join t_user_role ur on ur.USER_ID = u.USER_ID,
t_role r
where r.ROLE_ID = ur.ROLE_ID
and u.USER_ID = tu.USER_ID and r.ROLE_ID=#{userParams.roleId})
</if>
<if test="userParams.mobile != null and userParams.mobile != ''">
AND tu.MOBILE =#{userParams.mobile}
</if>
<if test="userParams.username != null and userParams.username != ''">
AND tu.USERNAME like CONCAT('%',#{userParams.username},'%')
</if>
<if test="userParams.ssex != null and userParams.ssex != ''">
AND tu.SSEX =#{userParams.ssex}
</if>
<if test="userParams.status != null and userParams.status != ''">
AND tu.STATUS =#{userParams.status}
</if>
<if test="userParams.deptId != null and userParams.deptId != ''">
AND td.DEPT_ID =#{userParams.deptId}
</if>
<if test="userParams.createTime != null and userParams.createTime != ''">
AND DATE_FORMAT(tu.CREATE_TIME,'%Y%m%d') BETWEEN substring_index(#{userParams.createTime},'#',1) and substring_index(#{userParams.createTime},'#',-1)
</if>
</select>
对应mapper对应的方法
<T> IPage<User> findUsersByUser(Page<T> page, @Param("userParams") SearchUserParams userParams);
对应参数实体对象
@Data
public class SearchUserParams {
private String username;
private String mobile;
private String status;
private String ssex;
private Long deptId;
private String createTime;
private long adminType;
private String roleId;
}
通过if标签去判断条件是否满足,满足就拼接对应sql
注意在上面我们提到的条件拼接第一个是
where连接,而不是and应规避and风险保证sql语法正确 如下
<select id="findSearchCouponsPage" parameterType="cn.soboys.kmall.bean.web.params.SearchCouponParams" resultType="coupon">
select *
from coupon c
left join user_coupon uc on c.coupon_id = uc.coupon_id
WHERE 1 = 1
<if test="couponParams.userId != null and couponParams.userId != ''">
and uc.user_id =#{couponParams.userId}
</if>
<if test="couponParams.status != null and couponParams.status != ''">
and c.status =#{couponParams.status}
</if>
<if test="couponParams.couponId != null and couponParams.couponId != ''">
and c.coupon_id =#{couponParams.couponId}
</if>
<if test="couponParams.couponType != null and couponParams.couponType != ''">
and c.type =#{couponParams.couponType}
</if>
</select>
我们可以通过假定给他一个默认条件 WHERE 1 = 1来解决,也可以通过嵌套where标签来解决
mybatis的mapper特殊字符转移以及动态SQL条件查询的更多相关文章
- 8.mybatis动态SQL模糊查询 (多参数查询,使用parameterType)
多参数查询,使用parameterType.实例: 用户User[id, name, age] 1.mysql建表并插入数据 2.Java实体类 public class User { public ...
- MyBatis基础入门《十七》动态SQL
MyBatis基础入门<十七>动态SQL 描述: >> 完成多条件查询等逻辑实现 >> 用于实现动态SQL的元素主要有: > if > trim > ...
- Mysql动态多条件查询
动态多条件查询是一类经常遇到的问题. 在Mysql里面可以用语句简单的解决. SELECT * FROM product WHERE price = IF('{0}' = '', price, '{0 ...
- EntityFramework动态多条件查询与Lambda表达式树
在常规的信息系统中, 我们有需要动态多条件查询的情况, 例如UI上有多个选择项可供用户选择多条件查询数据. 那么在.net平台Entity Framework下, 我们用Lambd ...
- MyBatis入门3_mapper.xml优化(parameterType简写_NameSpace简写_sql片段_特殊字符处理)_动态SQL
本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 优化 1.起别名(一般不用,写全方便查看类出处) 以前 ...
- MyBatis 实践 -动态SQL/关联查询
MyBatis 实践 标签: Java与存储 动态SQL 动态SQL提供了对SQL语句的灵活操作,通过表达式进行判断,对SQL进行拼接/组装. if 对查询条件进行判断,如果输入参数不为空才进行查询条 ...
- MyBatis的动态SQL操作--查询
查询条件不确定,需要根据情况产生SQL语法,这种情况叫动态SQL,即根据不同的情况生成不同的sql语句. 模拟一个场景,在做多条件搜索的时候,
- Spring+SpringMVC+MyBatis深入学习及搭建(五)——动态sql
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6908763.html 前面有讲到Spring+SpringMVC+MyBatis深入学习及搭建(四)——My ...
- Java数据持久层框架 MyBatis之API学习七(动态 SQL详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
随机推荐
- DVWA靶场之SQL injection(blind)通关
盲注,顾名思义,无法从界面上直接查看到执行结果,一般的SQL注入基本绝迹,最多的就是盲注 基本步骤:(由于没有回显了,相比一般的SQL注入,也就不需要确定查询字段数.判断回显位置了) 判断注入类型 破 ...
- Android手机QQ的UI自动化实践
本文首发于果的博客园,原文链接:https://www.cnblogs.com/yuxiuyan/p/14992682.html, 转载请注明出处. UI自动化 我们为什么要搞UI自动化 可能很多同学 ...
- WinForm嵌入Web网页的解决方案
企业级信息化系统绝大部分采用BS架构实现,如门户网站.OA系统.电商网站等,通过浏览器输入Web网址即可访问,对于使用者来说非常便捷,对于开发维护者来说也非常方便,程序维护只需更新服务器即可,使用者无 ...
- NOIP 模拟 $38\; \rm c$
题解 \(by\;zj\varphi\) 发现就是一棵树,但每条边都有多种不同的颜色,其实只需要保留随便三种颜色即可. 直接点分治,将询问离线,分成一端为重心,和两端都不为重心的情况. 每次只关心经过 ...
- 获取SpringBean对象工具类
获取SpringBean工具类 SpringBeanUtil代码如下: package com.meeno.wzq.util; import org.springframework.beans.Bea ...
- 如果被问到 HTTP 协议,你真的能讲清楚吗?
前段时间,在和许久未见的老同学聊天时,突然被问到 http 协议到底是什么?脑海里面第一时间想起来的就是 request 请求.response 响应之类的词汇,但是这样讲他真的能知道是什么吗?我反问 ...
- java关键字native、static、final详解
native: native关键字说明其修饰的方法是一个原生态方法,方法对应的实现不是在当前文件,而是在用其他语言(如C和C++)实现的文件中.Java语言本身不能对操作系统底层进行访问和操作,但是可 ...
- leaflet 的 marker 弹框 iframe 嵌套代码
A页面 嵌套 B页面的代码 主要处理 leaflet 的 marker 的 popopen, marker的点击的显示/隐藏 pop 会导致pop中的页面的内容,消失,不在页面中,导致b ...
- 防止XSS 攻击集成springboot
1.配置相关数据 在配置文件中配置 # 防止XSS攻击 xss: # 过滤开关 enabled: true # 排除链接(多个用逗号分隔) excludes: /system/notice/* # 匹 ...
- 【nodejs】request 和 response 对象
request 和 response 对象的具体介绍: Request 对象 - request 对象表示 HTTP 请求,包含了请求查询字符串,参数,内容,HTTP 头部等属性.常见属性有: req ...