【Mybatis】MyBatis之动态SQL(六)
MyBatis 的强大特性之一便是它的动态 SQL,本章介绍动态 SQL
查看本章,请先阅读【Mybatis】MyBatis对表执行CRUD操作(三)。
本例表结构
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
if
if标签:用于逻辑判断,其中test属性,填写的是判断表达式(OGNL)
示例
1、EmployeeMapper新增Sql如下:
<!-- if:判断 -->
<select id="testConditionIf"
resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender from employee
<!--
test:判断表达式(OGNL) OGNL参照PPT或者官方文档。
c:if test 从参数中取值进行判断 遇见特殊符号应该去写转义字符: &&: -->
where 1 = 1
<if test="id != null">
AND id = #{id}
</if>
<!-- 表达式中,字符串使用''单引号引起来 -->
<if test="lastName != null and lastName.trim() != ''">
AND last_name = #{lastName}
</if>
<!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">
AND gender = #{gender}
</if>
<!-- 转义字符: && == && "" == ""-->
<if test="email != null && lastName!=""">
AND email = #{email}
</if>
</select>
2、EmployeeMapper接口中,新增方法
public List<Employee> testConditionIf(Employee employee);
3、测试方法
@Test
public void test001() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testConditionIf(new Employee(null, "0", null));
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
choose
有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
示例
1、EmployeeMapper新增Sql如下:
<!-- choose -->
<select id="testConditionChoose" resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender from employee
where 1 = 1
<choose>
<when test="id != null">
AND id = #{id}
</when>
<when test="lastName != null">
AND last_name = #{lastName}
</when>
<when test="gender != null">
AND gender = #{gender}
</when>
<when test="email != null">
AND email = #{email}
</when>
<otherwise>
AND 1 = 1
</otherwise>
</choose>
</select>
2、EmployeeMapper接口中,新增方法
public List<Employee> testConditionChoose(Employee employee);
3、测试方法
@Test
public void test002() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testConditionChoose(new Employee(1, null, null, null));
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
where
where标签:用于编写带where条件的sql,配合if标签使用,它会自动去除首个AND前缀。
示例
1、EmployeeMapper新增Sql如下:
<!-- if + where -->
<select id="testConditionIfWhere"
resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender from employee
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="lastName != null and lastName.trim() != ''">
AND last_name = #{lastName}
</if>
<if test="gender==0 or gender==1">
AND gender = #{gender}
</if>
<if test="email != null && lastName!=""">
AND email = #{email}
</if>
</where>
</select>
2、EmployeeMapper接口中,新增方法
public List<Employee> testConditionIfWhere(Employee employee);
3、测试方法
@Test
public void test003() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testConditionIfWhere(new Employee("小红", "1", null));
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
trim
trim标签:可以去掉字符串的首尾字符串,以及在字符串前后添加前后缀
示例
1、EmployeeMapper新增Sql如下:
<select id="testConditionIfTrim" resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender from employee
<!-- 后面多出的and或者or where标签不能解决
prefix="":前缀:trim标签体中是整个字符串拼串 后的结果。 prefix给拼串后的整个字符串加一个前缀
prefixOverrides="": 前缀覆盖: 去掉整个字符串前面多余的字符
suffix="":后缀 suffix给拼串后的整个字符串加一个后缀
suffixOverrides="" 后缀覆盖:去掉整个字符串后面多余的字符 -->
<trim prefix="where" prefixOverrides="AND">
<if test="id != null">
AND id = #{id}
</if>
<if test="lastName != null">
AND last_name = #{lastName}
</if>
<if test="gender != null">
AND gender = #{gender}
</if>
<if test="email != null">
AND email = #{email}
</if>
</trim>
</select>
2、EmployeeMapper接口中,新增方法
public List<Employee> testConditionIfTrim(Employee employee);
3、测试方法
@Test
public void test004() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testConditionIfTrim(new Employee(1, null, null, null));
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
foreach
动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候
示例
1、EmployeeMapper新增Sql如下:
<!-- foreach -->
<select id="testConditionForeach" resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender from employee
<!--
collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值 #{变量名}就能取出变量的值也就是当前遍历出的元素
-->
<foreach collection="ids" item="id" separator="," open="where id in (" close=")" >
#{id}
</foreach>
</select>
2、EmployeeMapper接口中,新增方法
public List<Employee> testConditionForeach(@Param("ids")List<Integer> ids);
3、测试方法
@Test
public void test005() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testConditionForeach(Arrays.asList(1, 2, 3, 4));
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
set
set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号
示例
1、EmployeeMapper新增Sql如下:
<!-- set -->
<update id="testConditionSet">
update employee
<set>
<if test="lastName != null">
last_name = #{lastName},
</if>
<if test="gender != null">
gender = #{gender},
</if>
<if test="email != null">
email = #{email},
</if>
</set>
where id = #{id}
</update>
2、EmployeeMapper接口中,新增方法
public boolean testConditionSet(Employee employee);
3、测试方法
@Test
public void test006() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
boolean f = mapper.testConditionSet(new Employee(1, "小白", "1", null));
System.out.println(f);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
4、执行结果
bind
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:
<select id="testConditionBind" resultType="Blog">
<bind name="pattern" value="'%' + keyword + '%'" />
SELECT * FROM employee WHERE last_name LIKE #{pattern}
</select>
sql
可以用来包含其他sql
<sql id="selectSql">select id, last_name lastName, gender from employee</sql> <select id="testConditionInclude" resultType="com.hd.test.pojo.Employee">
<include refid="selectSql"></include>
where id = 1
</select>
Mybatis中2个内置参数 _parameter和_databaseId
示例
1、EmployeeMapper新增Sql如下:
<!-- 两个内置参数:
不只是方法传递过来的参数可以被用来判断,取值。。。
mybatis默认还有两个内置参数:
_parameter:代表整个参数
单个参数:_parameter就是这个参数
多个参数:参数会被封装为一个map;_parameter就是代表这个map _databaseId:
如果配置了databaseIdProvider标签。 _databaseId就是代表当前数据库的别名mysql
如果没配置了databaseIdProvider标签。 _databaseId为null
-->
<select id="testInnerParameter" resultType="com.hd.test.pojo.Employee">
<if test="_databaseId == 'mysql'">select * from ${_parameter}</if>
<if test="_databaseId != 'mysql'">select * from ${_parameter} where 1 = 1</if>
</select>
2、mybatis-config.xml中的配置
<databaseIdProvider type="DB_VENDOR">
<!-- 为不同的数据库厂商起别名 -->
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
<property name="SQL Server" value="sqlserver"/>
</databaseIdProvider>
3、EmployeeMapper接口中,新增方法
public List<Employee> testInnerParameter(String tableName);
4、测试方法
@Test
public void test007() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> list = mapper.testInnerParameter("employee");
System.out.println(list.size());
for (Employee employee : list) {
System.out.println(employee);
} } catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
5、执行结果,从执行结果可以看出,_parameter == employee 参数,_databaseId == mysql 数据库别名
【Mybatis】MyBatis之动态SQL(六)的更多相关文章
- 【mybatis深度历险系列】mybatis中的动态sql
最近一直做项目,博文很长时间没有更新了,今天抽空,学习了一下mybatis,并且总结一下.在前面的博文中,小编主要简单的介绍了mybatis中的输入和输出映射,并且通过demo简单的介绍了输入映射和输 ...
- Mybatis入门之动态sql
Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...
- mybatis 详解------动态SQL
mybatis 详解------动态SQL 目录 1.动态SQL:if 语句 2.动态SQL:if+where 语句 3.动态SQL:if+set 语句 4.动态SQL:choose(when,o ...
- mybatis中的动态SQL
在实际开发中,数据库的查询很难一蹴而就,我们往往要根据各种不同的场景拼接出不同的SQL语句,这无疑是一项复杂的工作,我们在使用mybatis时,mybatis给我们提供了动态SQL,可以让我们根据具体 ...
- Mybatis映射文件动态SQL语句-01
因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句, UserMapper.xml <?xml version=" ...
- MyBatis实战之动态SQL
如果使用JDBC或者其他框架,很多时候你得根据需要去拼接SQL,这是一个麻烦的事情,而MyBatis提供对SQL语句动态的组装能力,而且它只有几个基本的元素,非常简单明了,大量的判断都可以在MyBat ...
- 6.Mybatis中的动态Sql和Sql片段(Mybatis的一个核心)
动态Sql是Mybatis的核心,就是对我们的sql语句进行灵活的操作,他可以通过表达式,对sql语句进行判断,然后对其进行灵活的拼接和组装.可以简单的说成Mybatis中可以动态去的判断需不需要某些 ...
- MyBatis注解配置动态SQL
MySQL创建表 DROP TABLE IF EXISTS `tb_employee`; CREATE TABLE `tb_employee` ( `id` int(11) NOT NULL AUTO ...
- mybatis框架(5)---动态sql
那么,问题来了: 什么是动态SQL? 动态SQL有什么作用? 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态S ...
- MyBatis进阶使用——动态SQL
MyBatis的强大特性之一就是它的动态SQL.如果你有使用JDBC或者其他类似框架的经验,你一定会体会到根据不同条件拼接SQL语句的痛苦.然而利用动态SQL这一特性可以彻底摆脱这一痛苦 MyBati ...
随机推荐
- New York is 3 hours ahead of California
New York is 3 hours ahead of California, 纽约时间比加州时间早三个小时, but it does not make California slow. 但加州时间 ...
- 逃逸分析(Escape Analysis)
一.什么是逃逸 逃逸是指在某个方法之内创建的对象,除了在方法体之内被引用之外,还在方法体之外被其它变量引用到:这样带来的后果是在该方法执行完毕之后,该方法中创建的对象将无法被GC回收,由于其被其它变量 ...
- Echart ,X轴显示的为tooltip内显示的一部分内容放在上面显示的一部分如下图所示
如图所示:X轴只显示tooltip部分内容解决方案 在xAxis下面,实现方法如下 axisLabel: { interval: 0, formatter:function(value) { var ...
- Helm介绍
1.为什么要用Helm? 首先在原来项目中都是基于yaml文件来进行部署发布的,而目前项目大部分微服务化或者模块化,会分成很多个组件来部署,每个组件可能对应一个deployment.yaml,一个se ...
- 算法之Python实现 - 002 : 换钱的最少货币数补充(每种货币只能使用一次)
[题目]:给定数组arr,arr中所有的值都为正数且不重复.每个值代表一种面值的货币,每种面值的货币仅可以使用一张,再给定一个整数aim代表要找的钱数,求组成aim的最少货币数. [代码1]:时间与额 ...
- CSS初识盒子
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- 导弹拦截问题(DP+贪心)
1. 拦截导弹(Noip1999) 某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度. ...
- Linux下使用ps命令查看某个进程文件的启动位置
ps -ef|grep shutdown ls -al /proc/4170
- python 获取随机字母
Python2 #-*- coding:utf- -*- import string #导入string这个模块 print string.digits #输出包含数字0~9的字符串 print st ...
- UBuntu16.04 安装docker
1.首先更新apt-get源,sudo apt-get update 2.再通过pip安装docker-compose 3.然后再安装docker.io,sudo apt install docker ...