前言

最近在开发项目的时候涉及到复杂的动态条件查询,但是mybaits本身不支持if elseif类似的判断但是我们可以间接通过 chose when otherwise 去实现其中choose为一个整体 when是if otherwise是else

快速使用

以前我们进行条件判断时候使用if标签进行判断,条件并列存在

		    <if test="seat_no != null and seat_no != '' ">
AND seat_no = #{seat_no}
</if>

现在 使用chose when otherwise条件只要有一个成立,其他的就不会再判断了。如果没有成立的条件则默认执行otherwise中的内容

		<choose>
<when test="……">
……
</when>
<otherwise>
……
</otherwise>
</choose>

以下是我自己真实使用的例子,并且经过了测试,仅供参考:

根据动态条件筛选查询用户信息

<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>
<choose>
<when test="userParams.adminType==4">
and tu.ADMIN_TYPE_ID in(2,3)
</when>
<otherwise>
<include refid="search"></include>
</otherwise>
</choose> </where> </select>
 <sql id="search">
<if test="userParams.adminType==null or userParams.adminType==''">
and tu.ADMIN_TYPE_ID in(0,1)
</if> <if test="userParams.adminType != null and userParams.adminType != ''">
and tu.ADMIN_TYPE_ID=#{userParams.adminType}
</if> <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>
</sql>

这里就用到啦 if else if 判断。 choose标签中when条件一但不成立,就会执行otherwise标签中的条件,判断语句,也就是我下面包含的sql片段条件

更详细的条件标签使用参考我这一篇文章点击进入

SQL片段拼接

我们再写sql语句的时候往往会有这样一些要求,一些重复的sql语句片段,我们不想重复去写,那么可以通过sql片段方式去抽离,公共sql然后在需要的地方去引用

MyBatis<sql> 元素用于定义一个 SQL 片段,用于分离一些公共的 SQL 语句,例如:SELECT 关键字和 WHERE 关键字之间的部分。其中:

id:唯一标识符,用于在其他地方使用 <include> 标签引用;

lang:设置字符编码;

databaseId:指定执行该 SQL 语句的数据库ID,数据库ID在 mybatis-cfg.xml 中的 中配置。

同时,你也能够看见 <sql> 标签中可以使用<include>、<trim>、<where>、<set>、<foreach>、<choose>、<if>、<bind>等标签定义复杂的 SQL 片段

简单使用定义sql片段如下:

<sql id="user_columns">
`user_id`, `name`, `sex`, `age`
</sql>

<sql> 标签中使用 <include> 标签引入定义的sql片段,如下:

<!-- 定义基础列 -->
<sql id="user_base_columns">
`user_id`, `name`
</sql> <!-- 定义一个SQL片段 -->
<sql id="user_columns">
<include refid="user_base_columns"/>, `sex`, `age`
</sql>

场景使用案例如:查询用户信息

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hxstrive.mybatis.sql.demo1.UserMapper">
<!-- 映射结果 -->
<resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.sql.demo1.UserBean">
<id column="user_id" jdbcType="INTEGER" property="userId" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap> <!-- 定义一个SQL片段 -->
<sql id="user_columns">
`user_id`, `name`, `sex`, `age`
</sql> <!-- 查询所有用户信息 -->
<select id="findAll" resultMap="RESULT_MAP">
select <include refid="user_columns" /> from `user`
</select> </mapper>

SQL参数取值和OGNL表达式

看到我们上面去值参数通过#{params}这种方式来去值的其中传进来的参数 #{xx} 就是使用的 OGNL 表达式。

Mybatis 官方文档中「XML 映射文件」模块里边,有解析到:

说当我们使用 #{} 类型参数符号的时候,其实就是告诉 Mybatis 创建一个预处理语句参数,通过 JDBC,这样的一个参数在 SQL 中会由一个 "?" 来标识,并传递到一个新的预处理语句中。



也就是说当我们使用 #{XX} OGNL 表达式的时候, 它会先帮我们生成一条带占位符的 SQL 语句,然后在底层帮我们设置这个参数:ps.setInt(1, id);

OGNL 是 Object-Graph Navigation Language 的缩写,对象-图行导航语言,语法为:#{ }。

是不是有点懵,不知道这是个啥?

OGNL 作用是在对象和视图之间做数据的交互,可以存取对象的属性和调用对象的方法,通过表达式可以迭代出整个对象的结构图

MyBatis常用OGNL表达式如下:

上述内容只是合适在MyBatis中使用的OGNL表达式,完整的表达式点击这里

MyBatis中可以使用OGNL的地方有两处:

  1. 动态SQL表达式中
  2. ${param}参数中

如下例子MySql like 查询:

<select id="xxx" ...>
select id,name,... from country
<where>
<if test="name != null and name != ''">
name like concat('%', #{name}, '%')
</if>
</where>
</select>

上面代码中test的值会使用OGNL计算结果。

例二,通用 like 查询:

<select id="xxx" ...>
select id,name,... from country
<bind name="nameLike" value="'%' + name + '%'"/>
<where>
<if test="name != null and name != ''">
name like #{nameLike}
</if>
</where>
</select>

这里的value值会使用OGNL计算。

注:对<bind参数的调用可以通过#{}或 ${} 方式获取,#{}可以防止注入。

在通用Mapper中支持一种UUID的主键,在通用Mapper中的实现就是使用了标签,这个标签调用了一个静态方法,大概方法如下:

<bind name="username_bind"
value='@java.util.UUID@randomUUID().toString().replace("-", "")' />

这种方式虽然能自动调用静态方法,但是没法回写对应的属性值,因此使用时需要注意。

  1. ${params}中的参数

上面like的例子中使用下面这种方式最简单

<select id="xxx" ...>
select id,name,... from country
<where>
<if test="name != null and name != ''">
name like '${'%' + name + '%'}'
</if>
</where>
</select>

这里注意写的是${'%' + name + '%'},而不是%${name}%,这两种方式的结果一样,但是处理过程不一样。

MyBatis中处理${}的时候,只是使用OGNL计算这个结果值,然后替换SQL中对应的${xxx},OGNL处理的只是${这里的表达式}。

这里表达式可以是OGNL支持的所有表达式,可以写的很复杂,可以调用静态方法返回值,也可以调用静态的属性值。

例子,条件判断入参属性值是否包含子字符串可以直接使用 contains判断

<foreach collection="list" item="item" index="index" separator="AND" open="(" close=")">

    <choose>
<when test='item.cname.contains("select") or item.cname.contains("checkbox") or item.cname.contains("date")'>
<if test='item.cname.contains("select") or item.cname.contains("checkbox")'>
find_in_set(#{item.value},base.${item.cname})
</if> <if test='item.cname.contains("date")'>
DATE_FORMAT(base.${item.cname},'%Y-%m-%d') = DATE_FORMAT(#{item.value},'%Y-%m-%d')
</if>
</when>
<otherwise>
base.${item.cname} = #{item.value}
</otherwise>
</choose> </foreach>

mybatis if else if 条件判断SQL片段表达式取值和拼接的更多相关文章

  1. SQL利用Case When Then多条件判断SQL 语句

    http://www.cnblogs.com/kevin2013/archive/2010/07/02/1769682.html SQL利用Case When Then多条件判断SQL ,用于sele ...

  2. sql中#与$取值

    在mapper.xml中#与$都是用来取值的 <update id="addUrl"> update user_power set url = #{newurl} wh ...

  3. 关于mybatis中基本类型条件判断问题

    零:sql动态语句中经常会有根据数据库某个字段状态进行判断的 如:status=0为未激活,status=1为激活的,那搜索未激活时: <if test="model.activeSt ...

  4. 多重条件判断SQL:用于用户名称,密码,权限的检测和判断

    string sqlstr = "select count(*) from tb_admin where 用户名='"+UserName+"'and 密码='" ...

  5. python 条件判断的三元表达式

    示例:求两数中最大者 在JavaScript中代码如下: x = 1; y = 2; console.log(x > y ? x : y) 在python中代码如下: # 条件为真时的返回结果 ...

  6. Sql server 函数--取值年月

    GetDate()是获取当前时间 1.例如获取年月类似 201706 需要改为语句: Select Datename(year,GetDate())+Datename(month,GetDate())

  7. SpringBoot使用Mybatis注解开发教程-分页-动态sql

    代码示例可以参考个人GitHub项目kingboy-springboot-data 一.环境配置 1.引入mybatis依赖 compile( //SpringMVC 'org.springframe ...

  8. if 条件判断

    逻辑判断的布尔值(true&false) 1.逻辑值(bool)用来表示诸如:对与错,真与假,非于空等概念. 2.逻辑值包含了两个值:--true:表示非空的量(比如:string,tuple ...

  9. Perl if条件判断

    Perl 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 条件判断常用: True         #布尔值 not True   #布尔值 ! True    ...

随机推荐

  1. DVWA靶场之SQL Injection通关

    SQL注入,一个大概的手工流程: 判断是否有注入,什么类型 破解SQL语句中查询的字段数是多少 确定回显位置 破库 破表 破字段 获得内容 Low: <?php if( isset( $_REQ ...

  2. 题解 math

    传送门 赛时用一个奇怪的方法过掉了 首先\(b_i\)的有效范围是\([0, k-1]\) 发现不同的\(a_i*b_i\)会有很多重的 考虑把\(a_i\%k\),然后由小到大排序 按顺序扫,如果某 ...

  3. 旧手机改造成web服务器并实现内网穿透

    前几天由于gitee的审核引擎一通乱杀,使得gitee pages停止提供服务,心生更换服务器或者其他pages托管的想法,看了看价格感人的云服务器以及空空的钱包,这时,脑子有个奇怪的想法飘过,自己搞 ...

  4. tcp为什么要三次握手,tcp为什么可靠

    转自 : https://www.cnblogs.com/LUO77/p/5771237.html大体看过,没有深入研究,有需要时继续看. 为什么不能两次握手:(防止已失效的连接请求又传送到服务器端, ...

  5. 十七:使用JDBC处理MySQL大数据

    一.基本概念 大数据也称之为LOB(Large Objects),LOB又分为:clob和blob,clob用于存储大文本,blob用于存储二进制数据,例如图像.声音.二进制文等. 在实际开发中,有时 ...

  6. 深入浅出Mybatis系列(二)---Mybatis入门

    一.Mybatis环境搭建及简单实例 1. 新建web项目, 添加依赖包:mybatis包.数据库驱动包(我使用的是mysql).日志包(我使用的是log4j), 由于我的是maven项目, 那么添加 ...

  7. Javascript - Vue - webpack + vue-cil

    cnpm(node package manager)和webpack模块 npm是运行在node.js环境下的包管理工具(先安装node.js,再通过命令 npm install npm -g 安装n ...

  8. MZY项目笔记:session歧路

    from my typora MZY项目笔记:session歧路 文章目录 MZY项目笔记:session歧路 那该怎么办? 1. 手动加上cookie的header. 2.自己模拟一个Session ...

  9. java8时间类API安全问题(赠送新的时间工具类哟)

    LocalDateTime等新出的日期类全是final修饰的类,不能被继承,且对应的日期变量都是final修饰的,也就是不可变类.赋值一次后就不可变,不存在多线程数据问题. simpleDateFor ...

  10. rabbitMq可靠消息投递之交换机备份

    //备份队列 @Bean("alternate_queue") public Queue alternate_queue() { return new Queue("al ...