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. pmm-server监控mysql

    https://blog.csdn.net/RunzIyy/article/details/104635680?utm_medium=distribute.pc_relevant.none-task- ...

  2. centos8安装sersync为rsync实现实时同步

    一,查看本地centos的版本: [root@localhost lib]# cat /etc/redhat-release CentOS Linux release 8.1.1911 (Core) ...

  3. centos8平台使用rpm管理软件包

    一,什么是rpm rpm是redhat package manager redhat的软件包管理器 说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/a ...

  4. jmeter静默压测+可视化

    静默压测自动化脚本auto_stress_test.sh #!/usr/bin/env bash export jmx_template="test2" export suffix ...

  5. Vue踩坑日记-This dependency was not found:element-ui.js

    该问题为在Vue启动项目时候报错找不到element-ui模块 解决办法:打开CMD 控制台 CD到项目根目录 我的目录(C:\Users\Administrator\Desktop\cms-heli ...

  6. Microsoft.Extensions.DependencyInjection中的Transient依赖注入关系,使用不当会造成内存泄漏

    Microsoft.Extensions.DependencyInjection中(下面简称DI)的Transient依赖注入关系,表示每次DI获取一个全新的注入对象.但是使用Transient依赖注 ...

  7. LinkBlockedQueue的c++实现

    c++链表实现的阻塞队列 最近从java源码里发现了阻塞队列的实现,觉得非常有趣. 首先,介绍下什么是阻塞队列.阻塞队列代表着一个队列可以线程安全的往该队列中写数据和从该队列中读数据.也就是说,我们可 ...

  8. ret2libc--ROP(pwn)漏洞入门分析

    背景知识 fflush 函数,清理缓冲区. fflush(stdout) 一次性输出以上缓冲区所有数据 read(0,&buf,0xAu) 0代表标准输入,标准输出1,标准错误2,&b ...

  9. 常用的实现Javaweb页面跳转的方式

    我们有两大种方式来实现页面跳转:1.JS(javascript):2.jsp跳转 先说jsp(金j三s胖p):1.转发:request.getRequestDispatcher("1.jsp ...

  10. D. Road to Post Office 解析(思維)

    Codeforce 702 D. Road to Post Office 解析(思維) 今天我們來看看CF702D 題目連結 題目 略,請直接看原題. 前言 原本想說會不會也是要列式子解或者二分搜,沒 ...