MyBatis —— 第二十九章 MyBatis 映射文件深入
1. 动态 SQL 语句
1.1. 动态 SQL 语句描述
MyBatis 的映射文件中,前面我们的 SQL 都是比较简单的,有时候业务逻辑复杂时,我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 语句就不能满足要求了。
参考官方文档,描述如下:
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 = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</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=", ">
#{id}
</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 = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
</where>
</select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser" />
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=", ">
#{id}
</foreach>
</where>
</select>
3. 知识要点
MyBatis 映射文件配置:
<select>
:查询<insert>
:插入<update>
:修改<delete>
:删除<where>
:where 条件<if>
:if 判断<foreach>
:循环<sql>
:SQL 片段抽取