1.动态SQL简介

动态 SQL是MyBatis强大特性之一.

动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似.

MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作.

2.if

1).实现DynamicSQL

public interface EmployeeMapperDynamicSQL {
public List<Employee> getEmpsByCondtionIf(Employee employee);
}

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- 查询员工:携带指定字段查询条件就带上该字段的值 -->
<!-- public List<Employee> getEmpsByCondtionIf(Employee employee) -->
<select id="getEmpsByCondtionIf" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee
<!-- where:根据条件包含 where 子句 -->
where
<!-- test:判断表达式(OGNL) -->
<!-- OGNL语法参照PPT或者官方文档:http://commons.apache.org/proper/commons-ognl/language-guide.html -->
<!-- 从参数中取值进行判断,如果遇到特殊符号去写转义字符,查W3C HTML ISO-8859-1 参考手册 -->
<if test="id!=null">
id=#{id}
</if>
<!-- <if test="lastName!=null and lastName!="""> -->
<!-- <if test="lastName!=null && lastName!=''"> -->
<if test="lastName!=null && lastName!=""">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!=""">
and email=#{email}
</if>
<!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</select>
</mapper>

  

//			select * from tbl_employee WHERE id=? and last_name like ? and email=?
// Employee employee = new Employee(3, "%e%","atguigu@atguigu.com", null);
//select * from tbl_employee WHERE id=? and last_name like ?
Employee employee = new Employee(null, "%e%",null, null);
List<Employee> emps = mapper.getEmpsByCondtionIf(employee);
for(Employee emp:emps) {
System.out.println(emp);
}

  

2.choose

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用.针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句.

	public List<Employee> getEmpByConditionChoose(Employee employee);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- public List<Employee> getEmpByConditionChoose(Employee employee) -->
<select id="getEmpByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee
<where>
<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="lastName!=null">
last_name like #{lastName}
</when>
<when test="email!=null">
email = #{email}
</when>
<otherwise>
gender = 0
</otherwise>
</choose>
</where>
</select>
</mapper>

  

			//测试choose
Employee employee = new Employee(3, "%e%",null, null);
List<Employee> list = mapper.getEmpByConditionChoose(employee);
for(Employee emp:list) {
System.out.println(emp);
}

  

3.trim

1).where

	public List<Employee> getEmpsByCondtionTrim(Employee employee);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- public List<Employee> getEmpsByCondtionTrim(Employee employee) -->
<select id="getEmpsByCondtionTrim" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee
<!-- 后面多出的and或者or where标签不能解决,我们使用trim定制where元素功能 -->
<!-- 自定义字符串的截取规则 -->
<!-- trim:根据条件包含 where 子句 -->
<!-- trim标签体中是整个字符串拼串 后的结果 -->
<!-- 通过自定义 trim 元素来定制 where 元素的功能 -->
<!-- prefix:前缀;prefix给拼串后的整个字符串加一个前缀 如:where <===> <trim prefix="where"> -->
<!-- prefixOverrides:前缀覆盖;去掉整个字符串前面多余的字符 -->
<!-- suffix:后缀;suffix给拼串后的整个字符串加一个后缀 -->
<!-- suffixOverrides:后缀覆盖;去掉整个字符串后面多余的字符 -->
<trim prefix="where" suffixOverrides="and">
<if test="id!=null">
id=#{id} and
</if>
<if test="lastName!=null && lastName!=""">
last_name like #{lastName} and
</if>
<if test="email!=null and email.trim()!=""">
email=#{email} and
</if>
<!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">
gender=#{gender}
</if>
</trim>
</select>
</mapper>

  

	@Test
public void testDynamicSql() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
// select * from tbl_employee WHERE id=? and last_name like ? and email=?
// Employee employee = new Employee(3, "%e%","atguigu@atguigu.com", null);
//select * from tbl_employee WHERE id=? and last_name like ?
Employee employee = new Employee(3, "%e%",null, null);
List<Employee> emps = mapper.getEmpsByCondtionIf(employee);
for(Employee emp:emps) {
System.out.println(emp);
} //查询的时候如果某些条件没带可能sql拼装会有问题
//1、给where后面加上1=1,以后的条件都and xxx.
//2、mybatis使用where标签来将所有的查询条件包括在内。
//mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
//where只会去掉第一个多出来的and或者or。 //测试Trim
List<Employee> emps2 = mapper.getEmpsByCondtionTrim(employee);
for(Employee emp:emps2) {
System.out.println(emp);
} } finally {
// : handle finally clause
openSession.close();
}
}

  

2).set

①.使用set更新

	public void  updateEmp(Employee employee);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<update id="updateEmp">
<!-- set:更新拼串 -->
<!-- set标签的使用 -->
update tbl_employee
<set>
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</set>
where id=#{id}
</update>
</mapper>

  

			//调试set标签
Employee employee = new Employee(1, "Adminn",null, null);
mapper.updateEmp(employee);
openSession.commit();

  

②.使用trim拼串更新

	public void  updateEmp(Employee employee);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- public void updateEmp(Employee employee) -->
<update id="updateEmp">
<!-- Trim:更新拼串 -->
update tbl_employee
<trim prefix="set" suffixOverrides=",">
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</trim>
where id=#{id}
</update>
</mapper>

  

			//调试set标签
Employee employee = new Employee(1, "Adminn",null, null);
mapper.updateEmp(employee);
openSession.commit();

  

4.foreach

动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候.

当迭代列表、集合等可迭代对象或者数组时;index是当前迭代的次数,item的值是本次迭代获取的元素.

当使用字典(或者Map.Entry对象的集合)时,index是键,item是值.

1).MySQL

(1).遍历记录

	//查询员工id'在给定集合中的
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- public List<Employee> getEmpsByConditionForeach(List<Integer> ids) -->
<select id="getEmpsByConditionForeach" resultType="com.atguigu.mybatis.bean.Employee">
<!-- collection:指定要遍历的集合;list类型的参数会特殊处理封装在map中,map的key就是list -->
<!-- item:当前遍历出的元素赋值给指定的变量 -->
<!-- separator:每个元素之间的分隔符 -->
<!-- open:遍历出所有结果拼接一个开始的字符 -->
<!-- close:遍历出所有结果拼接一个结束的字符 -->
<!-- index:索引;遍历list的时候是index就是索引,item就是当前值;遍历map的时候index表示的就是map的key,item就是map的值 -->
<!-- #{变量名}:能取出变量的值也就是当前遍历出的元素 -->
select * from tbl_employee
<foreach collection="ids" item="item_id" separator="," open="where id in(" close=")">
#{item_id}
</foreach>
</select>
</mapper>

  

			//测试foreach
List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3,4));
for(Employee emp : list) {
System.out.println(emp);
}

  

(2).批量保存记录1

	public void addEmps(@Param("emps")List<Employee> emps);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- 批量保存数据 -->
<!-- MySQL下批量保存:可以foreach遍历 mysql支持values(),(),()语法 -->
<!-- public void addEmps(@Param("emps")List<Employee> emps) -->
<!-- insert 方式一 -->
<!-- 推荐使用inert 方式一 -->
<insert id="addEmps">
insert into tbl_employee(last_name,email,gender,d_id)
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
</mapper>

  

			List<Employee> emps = new ArrayList<>();
emps.add(new Employee(null, "smith", "smith@atguigu.com", "1",new Department(1)));
emps.add(new Employee(null, "allen", "allen@atguigu.com", "0",new Department(1)));
mapper.addEmps(emps);
openSession.commit();

  

(3).批量保存记录2

	public void addEmps(@Param("emps")List<Employee> emps);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- insert 方式二 -->
<!-- public void addEmps(@Param("emps")List<Employee> emps) -->
<!-- 这种方式需要数据库连接属性allowMultiQueries=true;
这种分号分隔多个sql可以用于其他的批量操作(删除,修改) -->
<insert id="addEmps">
<foreach collection="emps" item="emp" separator=";">
insert into tbl_employee(last_name,email,gender,d_id)
values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
</mapper>

  

			List<Employee> emps = new ArrayList<>();
emps.add(new Employee(null, "smith", "smith@atguigu.com", "1",new Department(1)));
emps.add(new Employee(null, "allen", "allen@atguigu.com", "0",new Department(1)));
mapper.addEmps(emps);
openSession.commit();

  

2).Oracle

(1).批量保存1

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<insert id="addEmps" databaseId="oracle">
<!-- oracle第一种批量方式 -->
<!-- <foreach collection="emps" item="emp" open="begin" close="end;">
insert into employees(employee_id,last_name,email)
values(employees_seq.nextval,#{emp.lastName},#{emp.email});
</foreach>
</insert>
</mapper>

(2).批量保存2

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<insert id="addEmps" databaseId="oracle">
<!-- oracle第二种批量方式 -->
insert into employees(
<!-- 引用外部定义的sql -->
<include refid="insertColumn">
<property name="testColomn" value="abc"/>
</include>
)
<foreach collection="emps" item="emp" separator="union"
open="select employees_seq.nextval,lastName,email from("
close=")">
select #{emp.lastName} lastName,#{emp.email} email from dual
</foreach>
</insert>
</mapper>

  

5.bind

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文.

1).bind

若在 mybatis 配置文件中配置了 databaseIdProvider , 则可以使用 “_databaseId”变量,这样就可以根据不同的数据库厂商构建特定的语句.

	public List<Employee> getEmpsTestInnerParameter(Employee employee);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- public List<Employee> getEmpsTestInnerParameter(Employee employee) -->
<!-- mybatis默认还有两个内置参数:_parameter|_databaseId -->
<!-- _parameter:代表整个参数;单个参数:_parameter就是这个参数;多个参数:参数会被封装为一个map,_parameter就是代表这个map -->
<!-- _databaseId:如果配置了databaseIdProvider标签;_databaseId就是代表当前数据库的别名 -->
<select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
<if test="_databaseId=='mysql'">
select * from tbl_employee
<if test="_parameter!=null">
where last_name like #{lastName}
</if>
</if>
<if test="_databaseId=='oracle'">
select * from employees
<if test="_parameter!=null">
where last_name like #{_parameter.lastName}
</if>
</if>
</select>
</mapper>

  

	@Test
public void testInnerParam() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee2 = new Employee();
employee2.setLastName("%e%");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) {
System.out.println(employee);
}
}finally{
openSession.close();
}
}

  

2).SQL片段

	public void addEmps(@Param("emps")List<Employee> emps);

  

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperDynamicSQL">
<!-- insert 方式三 -->
<insert id="addEmps">
insert into tbl_employee(
<include refid="insertColumn"></include>
)
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
<!-- 抽取可重用的sql片段;方便后面引用 -->
<!-- 1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用 -->
<!-- 2、include来引用已经抽取的sql -->
<!-- 3、include还可以自定义一些property,sql标签内部就能使用自定义的属性 -->
<!-- include-property:取值的正确方式${prop} #{不能使用这种方式} -->
<sql id="insertColumn">
<if test="_databaseId=='oracle'">
employee_id,last_name,email
</if>
<if test="_databaseId=='mysql'">
last_name,email,gender,d_id
</if>
</sql>
</mapper>

  

	@Test
public void testBatchSave() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
List<Employee> emps = new ArrayList<>();
emps.add(new Employee(null, "smith", "smith@atguigu.com", "1",new Department(1)));
emps.add(new Employee(null, "allen", "allen@atguigu.com", "0",new Department(1)));
mapper.addEmps(emps);
openSession.commit();
}finally {
openSession.close();
}
}

6.OGNL

参考文档:http://commons.apache.org/proper/commons-ognl/language-guide.html

https://mybatis.org/mybatis-3/zh/dynamic-sql.html

04、MyBatis DynamicSQL(Mybatis动态SQL)的更多相关文章

  1. 【mybatis深度历险系列】mybatis中的动态sql

    最近一直做项目,博文很长时间没有更新了,今天抽空,学习了一下mybatis,并且总结一下.在前面的博文中,小编主要简单的介绍了mybatis中的输入和输出映射,并且通过demo简单的介绍了输入映射和输 ...

  2. Mybatis入门之动态sql

    Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...

  3. mybatis 详解------动态SQL

    mybatis 详解------动态SQL   目录 1.动态SQL:if 语句 2.动态SQL:if+where 语句 3.动态SQL:if+set 语句 4.动态SQL:choose(when,o ...

  4. mybatis中的动态SQL

    在实际开发中,数据库的查询很难一蹴而就,我们往往要根据各种不同的场景拼接出不同的SQL语句,这无疑是一项复杂的工作,我们在使用mybatis时,mybatis给我们提供了动态SQL,可以让我们根据具体 ...

  5. Mybatis映射文件动态SQL语句-01

    因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句, UserMapper.xml <?xml version=" ...

  6. 6.Mybatis中的动态Sql和Sql片段(Mybatis的一个核心)

    动态Sql是Mybatis的核心,就是对我们的sql语句进行灵活的操作,他可以通过表达式,对sql语句进行判断,然后对其进行灵活的拼接和组装.可以简单的说成Mybatis中可以动态去的判断需不需要某些 ...

  7. MyBatis注解配置动态SQL

    MySQL创建表 DROP TABLE IF EXISTS `tb_employee`; CREATE TABLE `tb_employee` ( `id` int(11) NOT NULL AUTO ...

  8. mybatis框架(5)---动态sql

    那么,问题来了: 什么是动态SQL? 动态SQL有什么作用? 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态S ...

  9. MyBatis进阶使用——动态SQL

    MyBatis的强大特性之一就是它的动态SQL.如果你有使用JDBC或者其他类似框架的经验,你一定会体会到根据不同条件拼接SQL语句的痛苦.然而利用动态SQL这一特性可以彻底摆脱这一痛苦 MyBati ...

随机推荐

  1. go cap和len区别

    首先要搞清楚容量和长度的区别: 容量是指底层数组的大小,长度指可以使用的大小 容量的用处在哪?在与当你用 appen d扩展长度时,如果新的长度小于容量,不会更换底层数组,否则,go 会新申请一个底层 ...

  2. 通透,23 个问题 TCP 疑难杂症全解析

    每个时代,都不会亏待会学习的人. 在进入今天主题之前我先抛几个问题,这篇文章一共提出 23 个问题. TCP 握手一定是三次?TCP 挥手一定是四次? 为什么要有快速重传,超时重传不够用?为什么要有 ...

  3. Python核心编程之生成器

    生成器 1. 什么是生成器 大家知道通过列表生成式(不知道的可自行百度一下),我们可以直接创建一个列表,但是,受内存限制,列表内容肯定是有限的.比如我们要创建一个包含100万个元素的列表,这100万个 ...

  4. Ubuntu20.4安装

    官网下载镜像 https://releases.ubuntu.com/20.04/ubuntu-20.04-live-server-amd64.iso 挂载开装 选语言 选键盘 网络设置DHCP到地址 ...

  5. 一口气看完45个寄存器,CPU核心技术大揭秘

    序言 前段时间,我连续写了十来篇CPU底层系列技术故事文章,有不少读者私信我让我写一下CPU的寄存器. 寄存器这个太多太复杂,不适合写故事,拖了很久,总算是写完了,这篇文章就来详细聊聊x86/x64架 ...

  6. Redis入门之认识redis(一)

    第1章 非关系型数据库 1.1 NoSQL数据库概述 1) NoSQL(NoSQL = Not Only SQL ),意即"不仅仅是SQL",泛指非关系型的数据库. NoSQL 不 ...

  7. C++学习笔记---数据类型

    1.整型 C++中能够表示整型的类型有几下几种方式,区别在于所占内存空间不足 数据类型 占用空间 取值范围 short(短整型) 2字节 (-2^15~2^15-1) int(整型) 4字节 (-2^ ...

  8. WSL2 + Docker + IDEA 开发到发布一步到位

    摘要:本文主要介绍了如何用WSL2.Docker.IDEA将Java应用从开发到发布一步到位. 上次介绍了如何在Windows(WSL2) Linux子系统中搭建搭建Docker环境,这次将利用上次搭 ...

  9. 《JavaScript高级程序设计》——第四章 变量、作用域和内存管理

    JavaScript变量可以用保存两种类型的值:基本类型值和引用类型值.基本类型的值源自以下基本类型数据:Undefined.Null.Boolean.Number和String. 从一个变量向另一个 ...

  10. Codeforces Round #679 (Div. 2, based on Technocup 2021 Elimination Round 1)

    考场上只做出来四道,第二天一早就写出来了E,蛮绝望的. A Finding Sasuke 水构造 #include <cstdio> #include <algorithm> ...