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”,是为了避免后续条件不满足时候报错,那有没有办法避免这种写法呢?
当然有,就是接下来要说的,标签会自动判断如果包含的标签中有返回值的话,就在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标签
的作用是去除特殊的字符串,它的prefix属性代表语句的前缀,prefixoverrides属性代表需要去除的哪些特殊字符串,prefixoverrides属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的),后缀的处理和前缀一样。
trim标签的主要属性如下
- prefix:前缀覆盖并增加其内容。
- suffix:后缀覆盖并增加其内容。
- prefixoverrides:前缀判断的条件。
- suffixoverrides:后缀判断的条件。
举两个例子。
- 使用前缀属性
<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 suffix=" set " suffixoverrides=","> <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>
四、标签
的作用是遍历集合,它能够很好地支持数组和list、set接口的集合的遍历,往往和sql中的in组合比较多。
foreach标签的主要属性如下
- item:表示循环中当前的元素。
- index:表示当前元素在集合的位置下标。
- collection:配置list的属性名等。
- open和close:配置的是以什么符号将这些集合元素包装起来。
- separator:配置的是各个元素的间隔符。
举个例子:
<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>
到此mybatis的动态sql的常用功能已经介绍完了,有问题欢迎留言沟通哦!
推荐阅读
1.一分钟带你了解下spring security!
2.一分钟带你学会利用mybatis-generator自动生成代码!
3.手把手带你实战下spring的七种事务传播行为
4.springboot系列-整合mybatis(注解方式)
5.springboot系列-整合mybatis(xml配置方式)
java碎碎念,一个坚持原创的公众号,为您提供一系列系统架构、微服务、java、springboot、springcloud等高质量技术文章。
如果觉得文章不错,希望可以随手转发或者”在看“哦,非常感谢哈!
关注下方公众号后回复「1024」,有惊喜哦!
本文由博客一文多发平台 openwrite 发布!