MyBatis的强大特性之一即是它的动态SQL,之前拼接的时候须要注意的空格、列表最后的逗号等,如今均可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下。spring
if是最经常使用的判断语句,主要用于实现某些简单的条件选择。基本使用示例以下:sql
<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>
上面的例子中使用了“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>的做用是去除特殊的字符串,它的prefix属性表明语句的前缀,prefixOverrides属性表明须要去除的哪些特殊字符串,prefixOverrides属性会忽略经过管道分隔的文本序列(注意此例中的空格也是必要的),后缀的处理和前缀同样。springboot
trim标签的主要属性以下mybatis
举两个例子。架构
<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>
<foreach>的做用是遍历集合,它可以很好地支持数组和List、Set接口的集合的遍历,每每和sql中的in组合比较多。ide
foreach标签的主要属性以下微服务
举个例子:spa
<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的经常使用功能已经介绍完了,有问题欢迎留言沟通哦! code
推荐阅读
1.一分钟带你了解下Spring Security!
2.一分钟带你学会利用mybatis-generator自动生成代码!
3.手把手带你实战下Spring的七种事务传播行为
4.SpringBoot系列-整合Mybatis(注解方式)
5.SpringBoot系列-整合Mybatis(XML配置方式)
Java碎碎念,一个坚持原创的公众号,为您提供一系列系统架构、微服务、Java、SpringBoot、SpringCloud等高质量技术文章。
若是以为文章不错,但愿能够随手转发或者”在看“哦,很是感谢哈!
关注下方公众号后回复「1024」,有惊喜哦!