MyBatis 第二十九章 MyBatis 映射文件深入


MyBatis —— 第二十九章 MyBatis 映射文件深入


1. 动态 SQL 语句

1.1. 动态 SQL 语句描述

MyBatis 的映射文件中,前面我们的 SQL 都是比较简单的,有时候业务逻辑复杂时,我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 语句就不能满足要求了。

参考官方文档,描述如下:

DynamicSQL

1.2. 动态 SQL 之 <if>

我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。在 id 不为空时可以根据 id 查询,如果 username 不为空时还要加入用户名作为条件。这种情况我们在多条件组合查询中经常会遇到。

<select id="findByCondition" parameterType="user" resultType="user">
    select * from user 
    <where>
        <if test="id != 0">
            and id = #&#123;id&#125;
        </if>
        <if test="username != null">
            and username = #&#123;username&#125;
        </if>
        <if test="password != null">
            and password = #&#123;password&#125;
        </if>
    </where>
</select>

1.3. 动态 SQL 之 <foreach>

在传递一个可变的集合参数时,可以通过 <foreach> 标签来进行动态拼接

<select id="findByIds" parameterType="list" resultType="user">
    select * from user 
    <where>
        <foreach collection="list" open="id in(" close=")" item="id" separator=", ">
            #&#123;id&#125;
        </foreach>
    </where>
</select>

2. SQL 片段抽取

SQL 中可以将重复的 SQL 提取出来,使用时使用 include 引用即可,最终达到 SQL 重用的目的

<!-- Extract SQL fragments to simplify writing -->
<sql id="selectUser">
    select * from user
</sql>
<select id="findByCondition" parameterType="user" resultType="user">
    <include refid="selectUser" />
    <where>
        <if test="id != 0">
            and id = #&#123;id&#125;
        </if>
        <if test="username != null">
            and username = #&#123;username&#125;
        </if>
        <if test="password != null">
            and password = #&#123;password&#125;
        </if>
    </where>
</select>
<select id="findByIds" parameterType="list" resultType="user">
    <include refid="selectUser" />
    <where>
        <foreach collection="list" open="id in(" close=")" item="id" separator=", ">
            #&#123;id&#125;
        </foreach>
    </where>
</select>

3. 知识要点

MyBatis 映射文件配置:

  1. <select>查询
  2. <insert>插入
  3. <update>修改
  4. <delete>删除
  5. <where>where 条件
  6. <if>if 判断
  7. <foreach>循环
  8. <sql>SQL 片段抽取


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录