Mybatis中的动态SQL

2023-09-19 09:28:17
  • Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。

一、if(单独使用较少)

  • if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
  • 使用if时,通常在where后面添加一个恒成立条件1=1
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp where 1=1
	<if test="empName != null and empName !=''">
		and emp_name = #{empName}
	</if>
	<if test="age != null and age !=''">
		and age = #{age}
	</if>
	<if test="sex != null and sex !=''">
		and sex = #{sex}
	</if>
	<if test="email != null and email !=''">
		and email = #{email}
	</if>
</select>

 

   二、where         

where元素主要是用于简化查询语句中where部分的条件判断,where元素可以再<where>元素所在位置输出一个where关键字,而且还可以将后面条件多余的and或or关键字去掉,与其他元素搭配使用。

  • where和if一般结合使用:
    • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
    • 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<where>
		<if test="empName != null and empName !=''">
			emp_name = #{empName}
		</if>
		<if test="age != null and age !=''">
			and age = #{age}
		</if>
		<if test="sex != null and sex !=''">
			and sex = #{sex}
		</if>
		<if test="email != null and email !=''">
			and email = #{email}
		</if>
	</where>
</select>

 

三、trim

  • trim用于去掉或添加标签中的内容
  • 常用属性
    • prefix:在trim标签中的内容的前面添加某些内容
    • suffix:在trim标签中的内容的后面添加某些内容
    • prefixOverrides:在trim标签中的内容的前面去掉某些内容
    • suffixOverrides:在trim标签中的内容的后面去掉某些内容
  • 若trim中的标签都不满足条件,则trim标签没有任何效果。
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and|or">
		<if test="empName != null and empName !=''">
			emp_name = #{empName} and
		</if>
		<if test="age != null and age !=''">
			age = #{age} and
		</if>
		<if test="sex != null and sex !=''">
			sex = #{sex} or
		</if>
		<if test="email != null and email !=''">
			email = #{email}
		</if>
	</trim>
</select>
//测试类
@Test
public void getEmpByCondition() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	List<Emp> emps= mapper.getEmpByCondition(new Emp(null, "张三", null, null, null, null));
	System.out.println(emps);
}

结果如下:

四、choose、when、otherwise

  • choose、when、otherwise相当于if...else if..else
  • when至少要有一个,otherwise至多只有一个
<select id="getEmpByChoose" resultType="Emp">
	select * from t_emp
	<where>
		<choose>
			<when test="empName != null and empName != ''">
				emp_name = #{empName}
			</when>
			<when test="age != null and age != ''">
				age = #{age}
			</when>
			<when test="sex != null and sex != ''">
				sex = #{sex}
			</when>
			<when test="email != null and email != ''">
				email = #{email}
			</when>
			<otherwise>
				did = 1
			</otherwise>
		</choose>
	</where>
</select>
@Test
public void getEmpByChoose() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	List<Emp> emps = mapper.getEmpByChoose(new Emp(null, "张三", 23, "男", "123@qq.com", null));
	System.out.println(emps);
}

结果如下:

  • 相当于if a else if b else if c else d,只会执行其中一个

五、foreach

属性:

  • collection:设置要循环的数组或集合
  • item:表示集合或数组中的每一个数据
  • separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,
  • open:设置foreach标签中的内容的开始符
  • close:设置foreach标签中的内容的结束符

5.1  批量删除

<!--int deleteMoreByArray(Integer[] eids);-->
<delete id="deleteMoreByArray">
	delete from t_emp where eid in
	<foreach collection="eids" item="eid" separator="," open="(" close=")">
		#{eid}
	</foreach>
</delete>
@Test
public void deleteMoreByArray() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	int result = mapper.deleteMoreByArray(new Integer[]{6, 7, 8, 9});
	System.out.println(result);
}

结果如下:

 其中的xml文件里的SQL语句也可以为:

5.2  批量添加

<!--int insertMoreByList(@Param("emps") List<Emp> emps);-->
<insert id="insertMoreByList">
	insert into t_emp values
	<foreach collection="emps" item="emp" separator=",">
		(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
	</foreach>
</insert>
@Test
public void insertMoreByList() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	Emp emp1 = new Emp(null,"a",1,"男","123@321.com",null);
	Emp emp2 = new Emp(null,"b",1,"男","123@321.com",null);
	Emp emp3 = new Emp(null,"c",1,"男","123@321.com",null);
	List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
	int result = mapper.insertMoreByList(emps);
	System.out.println(result);
}

结果如下:

六、SQL标签(SQL片段)

  • sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
  • 声明sql片段:<sql>标签
<sql id="empColumns">eid,emp_name,age,sex,email</sql>
  • 引用sql片段:<include>标签
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select <include refid="empColumns"></include> from t_emp
</select>

更多推荐

2023研究生数学建模D题思路代码 区域双碳目标与路径规划研究

D题思路代码区域双碳目标与路径规划研究完整解题思路可看视频:2023华为杯研赛D题区域双碳目标与路径规划研究(附代码+全保姆教程)_哔哩哔哩_bilibili​www.bilibili.com/video/BV1Cm4y157CH/?spm_id_from=333.999.0.0问题一:区域碳排放量以及经济、人口、能源

Spring Security 用了那么久,你对它有整体把控吗?

文章目录1.ServletFilter:守门人的角色2.DelegatingFilterProxy:桥接Servlet和Spring的神器3.FilterChainProxy:SpringSecurity过滤器链的管家3.SecurityFilterChain:Security过滤器的串绳4.SpringSecurit

【Vue】避免Vue组件中常见的props默认值陷阱

1.对象和数组默认值的共享问题当你将一个对象或数组作为props的默认值时,它们会在组件的所有实例之间共享。这意味着如果一个组件修改了这个默认值,其他组件也会受到影响,因为它们共享同一个引用。陷阱:props:{userInfo:{type:Object,default:{}}}问题:如果一个组件修改了userInfo

基于vue3 + ant-design 自定义SVG图标iconfont的解决方案;ant-design加载本地iconfont.js不显示图标问题

基于vue3+ant-design自定义SVG图标iconfont的解决方案;ant-design加载本地iconfont.js不显示图标问题一、准备工作1、首先去阿里巴巴矢量图标库自定义添加自己的图标;网站地址https://www.iconfont.cn/整个步骤是:选择图标–添加到项目-项目设置-下载到本地已经选

Web Storage是什么?Web Storage详解

WebStorag是HTML5引入的一个非常重要的功能,可以将数据存储在本地,如保存用户的偏好设置、复选框的选中状态、文本框默认填写的值等。用户在浏览器中刷新网页时,网页通过WebStorage就可以知道用户之前所做的一些修改,而不需要将用户修改的内容存储在服务器端。WebStorage类似于Cookie,但相比Coo

【docker安装Mysql并配置主从复制】

Mysql主从复制目的:是为了后面naocs集群的服务配置做准备工作准备工作准备至少两台虚拟机或服务器,安装好了docker,找到他们的ip地址后面操作都用xshell操作来代替拉取并启动mysql镜像和容器主机的命令为mysql01,对外端口用3310来连接dockerrun-d-p3310:3306-v/home/

ubuntu在线直接升级

前几天VMware上安装了ubuntu,当时的内核版本支持(ipguard,加密软件),后来ubuntu自动升级了linux内核,导致加入软件不支持,无法访问加密文件了。后来加密软件商更新了软件,但还是赶不上linux内核更新速度,还是不能用。之前我写过手动升级内核的方法,实在有些复杂,所以借助chatgpt的提示和摸

Vuex —— 状态管理 | Module

在前面讲到了关于Vuex数据状态管理的内容,讲了Vuex的五大核心属性,在这五大核心属性中就state、mutation和actions在前面介绍Vuex状态管理和讲Vuex中的同步和异步操作已经比较熟悉了,getter是基于state的计算属性,vue中computed从data中派生出的计算属性,vuex中gett

【校招VIP】java语言考点之嵌套类&内部类

考点介绍:嵌套类&内部类问题在校招面试中经常出现。以在一个类的内部定义另一个类,这种类称为嵌套类(nestedclasses),它有两种类型:静态嵌套类和非静态嵌套类。静态嵌套类使用很少最重要的是非静态嵌套类,也即是被称作为内部类(inner)。java语言考点之嵌套类&内部类-相关题目及解析内容可点击文章末尾链接查看

如何搭建Linux环境

W...Y的主页😊代码仓库分享💕当我们想要搭建一个Linux系统,我们应该怎么使用呢?今天我就带领大家搭建Linux系统!!!目录Linux环境安装双系统(不推荐)powwershell(不推荐)虚拟机+centos7镜像使用云服务器(推荐)XShell下的复制粘贴Linux环境安装双系统(不推荐)在计算机上安装L

Linux MQTT智能家居(源码使用分析)

文章目录前言一、连接服务器1.初始化客户端2.设置端口号设置IP地址3.连接服务器二、发布消息三、订阅消息总结前言本篇文章开始我们来分析一下大佬写的MQTT源码,并且来看看怎么样使用MQTT连接到服务器。MQTT源码地址:源码地址这里找到源码中的test.c进行分析:一、连接服务器1.初始化客户端首先使用mqtt_le

热文推荐