温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis中怎么实现动态SQL!

发布时间:2021-07-26 15:41:56 来源:亿速云 阅读:178 作者:Leah 栏目:数据库

这篇文章将为大家详细讲解有关MyBatis中怎么实现动态SQL!,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、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标签的主要属性如下

  • 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 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标签的主要属性如下

  • 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!就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI