MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格、列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下。
一、if标签
if是最常用标签,经常用在判断语句上,可以实现某些简单的条件选择。基本使用示例如下:
- <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User">
- select * from user where 1=1
- <if test="name != null and name != ''">
- and name = #{name}
- </if>
- <if test="age != null ">
- and age = #{age}
- </if>
- </select>
二、where标签
上面的例子中使用了“1=1”,是为了避免后续条件不满足时候报错,那有没有办法避免这种写法呢?
当然有,就是接下来要说的where,where标签会自动判断如果包含的标签中有返回值的话,就在sql中插入一个where,如果where标签最后返回的内容是以and 或者or开头的,也会被自动移除掉,上面例子中换成where标签后写法如下:
- <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User">
- select * from user
- <where>
- <if test="name != null and name != ''">
- and name = #{name}
- </if>
- <if test="age != null ">
- and age = #{age}
- </if>
- </where>
- </select>
三、trim标签
trim的作用是去除特殊的字符串,它的prefix属性代表语句的前缀,prefixOverrides属性代表需要去除的哪些特殊字符串,prefixOverrides属性会忽略通过管道分隔的字符,后缀的处理和前缀一样。
trim标签的主要属性如下
举两个例子。
使用前缀属性
- <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User">
- select * from user
- <trim prefix="WHERE" prefixOverrides="AND |OR " >
- <if test="name != null and name != ''">
- and name = #{name}
- </if>
- <if test="sex != null ">
- or sex = #{sex}
- </if>
- <if test="age != null ">
- and age = #{age}
- </if>
- </trim>
- </select>
使用后缀属性
- <update id="update" parameterType="Object">
- UPDATE user
- <trim prefix=" SET " prefixOverrides=",">
- <if test="id != null ">,id=#{id}</if>
- <if test="name != null ">,name=#{name}</if>
- <if test="age != null ">,age=#{age}</if>
- </trim>
- WHERE ID=#{id}
- </update>
四、foreach标签
foreach的作用是遍历集合,它能够很好地支持数组和List、Set接口的集合的遍历,往往和sql中的in组合比较多。
foreach标签的主要属性如下
举个例子:
- <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User">
- select * from user where id in
- <foreach item="id" index="index" collection="userList"
- open="(" separator="," close=")">
- #{id}
- </foreach>
- </select>
开发背景: 最近一段时间一直在做关于微信方面的网站应用开发,这段时间也收获的...
在实际开发过程中,发现以下的写法比较累赘,因为在后面的项目中,继续优化表单...
1、首先去官网下载FCKeditor2.6.5 多国语言版。http://ckeditor.com/download,...
比如: 如果你的查询语句是select * from admin where username="user" and pass...
socket编程是网络通信程序的编写涉及到应用层以下各层协议的选择。在传输层中我...
下载bootstrap的js,css文件: 在jsp中的应用: 第一步: 新建一个web项目 将boo...
大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全...
Grafana Tempo 是一个新的开源、大容量分布式跟踪后端。 Grafana 的 Tempo 是出...
etcd组件作为一个高可用强一致性的服务发现存储仓库. etcd作为一个受到ZooKeeper...
本文基于 SpringCloud, 用户发起点赞、取消点赞后先存入 Redis 中,再每隔两小时...