mybatis 详解(五)------动态SQL
目录
前面几篇博客我们通过实例讲解了用mybatis对一张表进行的CRUD操作,但是我们发现写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就是本篇所讲的使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。
我们以 User 表为例来说明:
1、动态SQL:if 语句
根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询
首先不使用 动态SQL 来书写
1
2
3
4
5
6
|
<select id= "selectUserByUsernameAndSex"
resultType= "user" parameterType= "com.ys.po.User" >
<!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一定要写id,
写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 -->
select * from user where username=#{username} and sex=#{sex}
</select> |
上面的查询语句,我们可以发现,如果 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断
1
2
3
4
5
6
7
8
9
10
|
<select id= "selectUserByUsernameAndSex" resultType= "user" parameterType= "com.ys.po.User" >
select * from user where
< if test= "username != null" >
username=#{username}
</ if >
< if test= "username != null" >
and sex=#{sex}
</ if >
</select> |
这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句
2、动态SQL:if+where 语句
1
2
3
4
5
6
7
8
9
10
11
12
|
<select id= "selectUserByUsernameAndSex" resultType= "user" parameterType= "com.ys.po.User" >
select * from user
<where>
< if test= "username != null" >
username=#{username}
</ if >
< if test= "username != null" >
and sex=#{sex}
</ if >
</where>
</select> |
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
3、动态SQL:if+set 语句
同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!-- 根据 id 更新 user 表的数据 --> <update id= "updateUserById" parameterType= "com.ys.po.User" >
update user u
<set>
< if test= "username != null and username != ''" >
u.username = #{username},
</ if >
< if test= "sex != null and sex != ''" >
u.sex = #{sex}
</ if >
</set>
where id=#{id}
</update> |
这样写,如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?
如果第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?
4、动态SQL:choose(when,otherwise) 语句
有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<select id= "selectUserByChoose" resultType= "com.ys.po.User" parameterType= "com.ys.po.User" >
select * from user
<where>
<choose>
<when test= "id !='' and id != null" >
id=#{id}
</when>
<when test= "username !='' and username != null" >
and username=#{username}
</when>
<otherwise>
and sex=#{sex}
</otherwise>
</choose>
</where>
</select>
|
也就是说,这里我们有三个条件,id,username,sex,只能选择一个作为查询条件
如果 id 不为空,那么查询语句为:select * from user where id=?
如果 id 为空,那么看username 是否为空,如果不为空,那么语句为 select * from user where username=?;
如果 username 为空,那么查询语句为 select * from user where sex=?
5、动态SQL:trim 语句
trim标记是一个格式化的标记,可以完成set或者是where标记的功能
①、用 trim 改写上面第二点的 if+where 语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<select id= "selectUserByUsernameAndSex" resultType= "user" parameterType= "com.ys.po.User" >
select * from user
<!-- <where>
< if test= "username != null" >
username=#{username}
</ if >
< if test= "username != null" >
and sex=#{sex}
</ if >
</where> -->
<trim prefix= "where" prefixOverrides= "and | or" >
< if test= "username != null" >
and username=#{username}
</ if >
< if test= "sex != null" >
and sex=#{sex}
</ if >
</trim>
</select>
|
prefix:前缀
prefixoverride:去掉第一个and或者是or
②、用 trim 改写上面第三点的 if+set 语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!-- 根据 id 更新 user 表的数据 --> <update id= "updateUserById" parameterType= "com.ys.po.User" >
update user u
<!-- <set>
< if test= "username != null and username != ''" >
u.username = #{username},
</ if >
< if test= "sex != null and sex != ''" >
u.sex = #{sex}
</ if >
</set> -->
<trim prefix= "set" suffixOverrides= "," >
< if test= "username != null and username != ''" >
u.username = #{username},
</ if >
< if test= "sex != null and sex != ''" >
u.sex = #{sex},
</ if >
</trim>
where id=#{id}
</update>
|
suffix:后缀
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
6、动态SQL: SQL 片段
有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
比如:假如我们需要经常根据用户名和性别来进行联合查询,那么我们就把这个代码抽取出来,如下:
1
2
3
4
5
6
7
8
9
|
<!-- 定义 sql 片段 --> <sql id= "selectUserByUserNameAndSexSQL" >
< if test= "username != null and username != ''" >
AND username = #{username}
</ if >
< if test= "sex != null and sex != ''" >
AND sex = #{sex}
</ if >
</sql> |
引用 sql 片段
1
2
3
4
5
6
7
8
|
<select id= "selectUserByUsernameAndSex" resultType= "user" parameterType= "com.ys.po.User" >
select * from user
<trim prefix= "where" prefixOverrides= "and | or" >
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid= "selectUserByUserNameAndSexSQL" ></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</trim>
</select> |
注意:①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where
7、动态SQL: foreach 语句
需求:我们需要查询 user 表中 id 分别为1,2,3的用户
sql语句:select * from user where id=1 or id=2 or id=3
select * from user where id in (1,2,3)
①、建立一个 UserVo 类,里面封装一个 List<Integer> ids 的属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.ys.vo;
import java.util.List;
public class UserVo {
//封装多个用户的id
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this .ids = ids;
}
} |
②、我们用 foreach 来改写 select * from user where id=1 or id=2 or id=3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<select id= "selectUserByListId" parameterType= "com.ys.vo.UserVo" resultType= "com.ys.po.User" >
select * from user
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from user where 1 = 1 and (id= 1 or id= 2 or id= 3 )
-->
<foreach collection= "ids" item= "id" open= "and (" close= ")" separator= "or" >
id=#{id}
</foreach>
</where>
</select> |
测试:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//根据id集合查询user表数据 @Test public void testSelectUserByListId(){
String statement = "com.ys.po.userMapper.selectUserByListId" ;
UserVo uv = new UserVo();
List<Integer> ids = new ArrayList<>();
ids.add( 1 );
ids.add( 2 );
ids.add( 3 );
uv.setIds(ids);
List<User> listUser = session.selectList(statement, uv);
for (User u : listUser){
System.out.println(u);
}
session.close();
} |
③、我们用 foreach 来改写 select * from user where id in (1,2,3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<select id= "selectUserByListId" parameterType= "com.ys.vo.UserVo" resultType= "com.ys.po.User" >
select * from user
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from user where 1 = 1 and id in ( 1 , 2 , 3 )
-->
<foreach collection= "ids" item= "id" open= "and id in (" close= ") " separator= "," >
#{id}
</foreach>
</where>
</select>
|
8、总结
其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。
"<script>" +
"SELECT id,sn,user_id,
"FROM oilcard "+
"<where>" +
"<if test=\"createdStart !=null \"> and created <![CDATA[ > ]]> #{createdStart}</if>" +
"<if test=\"createdEnd !=null \"> and created <![CDATA[ < ]]> #{createdEnd}</if>" +
"</where>" +
"order by order_time desc " +
"</script>"
http://pic.cnblogs.com/face/637525/20150826135046.png
【转载】 mybatis入门系列四之动态SQL的更多相关文章
-
MyBatis入门(四)---动态SQL
一.创建数据库表 1.1.创建表 USE `mybatis`; /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; C ...
-
mybatis学习笔记四(动态sql)
直接贴图,注解在代码上,其他的配置文件在学习一中就不贴了 1 数据库 2 实体类 package com.home.entity; /** * 此类是: 用户实体类 * @author hpc * @ ...
-
MyBatis学习 之 四、动态SQL语句
有些时候,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息.使用Oracle的序列.mysq ...
-
MyBatis基础入门《十七》动态SQL
MyBatis基础入门<十七>动态SQL 描述: >> 完成多条件查询等逻辑实现 >> 用于实现动态SQL的元素主要有: > if > trim > ...
-
mybatis入门系列二之输入与输出参数
mybatis入门系列二之详解输入与输出参数 基础知识 mybatis规定mapp.xml中每一个SQL语句形式上只能有一个@parameterType和一个@resultType 1. 返回 ...
-
精尽MyBatis源码分析 - MyBatis初始化(四)之 SQL 初始化(下)
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
-
MyBatis学习 之 三、动态SQL语句
目录(?)[-] 三动态SQL语句 selectKey 标签 if标签 if where 的条件判断 if set 的更新语句 if trim代替whereset标签 trim代替set choose ...
-
mybatis入门系列三之类型转换器
mybatis入门系列三之类型转换器 类型转换器介绍 mybatis作为一个ORM框架,要求java中的对象与数据库中的表记录应该对应 因此java类名-数据库表名,java类属性名-数据库表字段名, ...
-
C语言高速入门系列(四)
C语言高速入门系列(四) C语言数组 ---------转载请注明出处:coder-pig 贴心小提示:假设图看不清晰可右键另存为,应该就非常清晰了; 注意上面的代码都要自己过一遍哦! 本节引言: 经 ...
随机推荐
-
Code First05--CodeFirst中值对象
今天主要介绍EF Code First中一个高级部分:Value Object,中文翻译过来叫做值对象. 所谓的值对象就是一些没有生命周期,也没有业务逻辑上唯一标识符的类.哪些类是Entity,哪些类 ...
-
Storm拓扑的并行度(parallelism)介绍
Storm拓扑的并行度(parallelism)介绍 1.Storm分为3个主要实体,用于在Storm集群中运行拓扑 工作进程:Worker Process,也称为Worker ...
-
linux定时任务访问url
这次linux定时任务设置成功,也算是自己学习linux中一个小小的里程碑.:) 撒花撒花--- 以下操作均是在ubuntu 下操作的,亲测有效,其他的linux系统还望亲们自己去查.鞠躬感谢! 1 ...
-
关于App启动加载广告页面思路
需求 很多app(如淘宝.美团等)在启动图加载完毕后,还会显示几秒的广告,一般都有个跳过按钮可以跳过这个广告,有的app在点击广告页之后还会进入一个广告页面,点击返回进入首页.虽然说这个广告页面对用户 ...
-
开源工作流程引擎ccflow多人待办处理模式的详解
多人待办工作处理模式,也是待办处理模式.是当接受的节点是多个人的时候,如何处理待办? 根据不用的场景,ccbpm把多人在普通节点下的处理模式分为如下几种. 抢办模式: A发送到B ,B节点上有n个人可 ...
-
5.1_非监督学习之sckit-learn
非监督学习之k-means K-means通常被称为劳埃德算法,这在数据聚类中是最经典的,也是相对容易理解的模型.算法执行的过程分为4个阶段. 1.首先,随机设K个特征空间内的点作为初始的聚类中心. ...
-
python mysql模块
多次使用python操作mysql数据库,先与大家分享一下,关于如何使用python操作mysql数据库.mysql并不是python自带的模块,因此需要下载安装.(在windows平台下介绍该使用过 ...
-
中间人攻击利用框架bettercap测试
0x00前言 上篇提到内网渗透很有趣,这次就从一款新工具说起: bettercap 0x01简介 bettercap可用来实现各种中间人攻击,模块化,便携.易扩展 0x02特点 提到中间人攻击,最知名 ...
-
在php中如何用 union all统计总条数?
网上使用union all 查询记录总条数的参考资料比较少,所以记录下来,以便有同样需求的人使用. $rs_num = Db::query("select sum(a.b) as num f ...
-
建议41:使用argparse处理命令行参数
# -*- coding:utf-8 -*- ''' 以现阶段最好用的参数处理标准库是argparse ''' import argparse parser = argparse.ArgumentPa ...