温馨提示×

温馨提示×

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

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

Mybatis中xml的动态sql怎么实现

发布时间:2022-06-30 13:57:07 来源:亿速云 阅读:103 作者:iii 栏目:开发技术

这篇文章主要介绍“Mybatis中xml的动态sql怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Mybatis中xml的动态sql怎么实现”文章能帮助大家解决问题。

动态SQL简介

动态 SQL 是 MyBatis 的强大特性之一。

如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

一、#{}与${}区别#{}表示一个占位符,使用占位符可以防止sql注入,

$ {}通过${}可以将parameterType传入的内容拼接在sql中,不能防止sql注入,但是有时方便
例:

SELECT * FROM USER WHERE username LIKE '%${name}%'

再比如order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,应该写为:

ORDER BY ${columnName}

如果使用#{}将无法实现此功能。

二、传递包装类型

Java 类

public class UserVo {
    private Administration adm;  
    //自定义用户扩展类
    private UserCustom userCustom;
}

xml文件

<select id="findUserList" parameterType="userVo" resultType="UserCustom">
          SELECT * FROM adm where adm.sex=
          #{userCustom.sex} and adm.username LIKE '%${userCustom.username}%'
</select>

三、动态sql&mdash;类型

mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑.

总体说来mybatis 动态SQL 语句主要有以下几类:

  • if 语句 (简单的条件判断)

  • choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.

  • trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)

  • where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)

  • set (主要用于更新时)

  • foreach (在实现 mybatis in 语句查询时特别有用)

四、动态sql&mdash;详解

(一)if 语句处理

    <select id="getUnitListByUserId" resultType="com.xjrsoft.module.customer.stock.inv_storer.vo.InvStorerVo"
            parameterType="string">
        SELECT ins.USER_ID as user_id, ins.OPERATING_UNIT_ID as operating_unit_id, mou.`NAME` as operating_unit_name
        FROM `inv_storer` ins
        left join md_operating_unit mou on ins.OPERATING_UNIT_ID = mou.F_Id
        where ins.F_DeleteMark = 0
        and ins.F_EnabledMark = 1
        <if test="userId != null and userId != ''">
            and ins.USER_ID = #{userId}
        </if>
    </select>

(二)choose (when,otherwize)语句处理

choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
 select * from t_blog where 1 = 1 
 <choose>
 <when test="title != null">
 and title = #{title}
 </when>
 <when test="content != null">
 and content = #{content}
 </when>
 <otherwise>
 and owner = "owner1"
 </otherwise>
 </choose>
</select>

详解

  • when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,

  • 当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。

小结

所以上述语句的意思非常简单,当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。

(三)trim 语句处理

trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)

<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
select * from t_blog 
<trim prefix="where" prefixOverrides="and |or">
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
or owner = #{owner}
</if>
</trim>
</select>

详解

  • trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;

  • 可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;

正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能。

小结

trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码:

select * from user 
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> 
AND name=#{name}
</if>
<if test="gender != null and gender.length()>0"> 
AND gender=#{gender}
</if>
</trim>

假如说name和gender的值都不为null的话打印的SQL为:

select * from user where name = 'xx' and gender = 'xx'

在红色标记的地方是不存在第一个and的,上面两个属性的意思如下:

  • prefix:前缀

  • prefixoverride:去掉第一个and或者是or

update user
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0">
name=#{name} ,
</if>
<if test="gender != null and gender.length()>0">
gender=#{gender} , 
</if>
</trim>

假如说name和gender的值都不为null的话打印的SQL为:

update user set name='xx' , gender='xx' where id='x'

在红色标记的地方不存在逗号,而且自动加了一个set前缀和where后缀,上面三个属性的意义如下,其中prefix意义如上:

suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

suffix:后缀

(四)where 语句处理

<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
select * from t_blog 
<where>
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</where>
</select>

详解:

  • where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,

  • 如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;

此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。

小结

像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是:

select * from t_blog where content = #{content}

而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。

(五)foreach 语句处理

foreach (在实现 mybatis in 语句查询时特别有用):

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。

foreach元素属性

  • item表示集合中每一个元素进行迭代时的别名。

  • index指定一个名字,用于表示在迭代过程中,每次迭代到的位置。

  • open表示该语句以什么开始。

  • separator表示在每次进行迭代之间以什么符号作为分隔符。

  • close表示以什么结束。

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:

  • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

  • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

  • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key。

1、单参数List的类型

    <select id="getStoreroomListByIds" parameterType="string"
resultType="com.xjrsoft.module.customer.inv_shift_head.invShiftHead.dto.InvStoreroomDto">
        SELECT info.*
        FROM (
        SELECT isr.F_Id AS storeroom_id,
        isr.OPERATING_UNIT_ID as unit_id,
        mou.NAME as unit_name
        FROM `inv_storeroom` isr
        LEFT JOIN `md_operating_unit` AS mou ON isr.OPERATING_UNIT_ID = mou.F_Id
        WHERE isr.F_DeleteMark = 0
        AND isr.F_EnabledMark = 1
        AND mou.F_DeleteMark = 0
        AND mou.F_EnabledMark = 1
        ) AS info
        <where>
            <if test="ids != null and ids != ''">
                info.storeroom_id in
                <foreach collection="ids" item="item" close=")" open="(" separator=",">
                    #{item}
                </foreach>
            </if>
        </where>
    </select>

上述collection的值为list,对应的Mapper是这样的:

    /**
     * 根据库房id获取经营单元
     *
     * @param ids
     * @return
     */
    List<InvStoreroomDto> getStoreroomListByIds(@Param("ids") List<String> ids);

2、数组类型的参数

<select id="dynamicForeach3Test" resultType="com.mybatis.entity.User">
select * from t_user where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>

对应mapper:

public List<User> dynamicForeach3Test(int[] ids);

3、Map类型的参数

<select id="dynamicForeach4Test" resultType="com.mybatis.entity.User">
select * from t_user where username like '%${username}%' and id in
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>

mapper 应该是这样的接口:

/**mybatis Foreach测试 */
public List<User> dynamicForeach4Test(Map<String, Object> params);

关于“Mybatis中xml的动态sql怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

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

AI