0、动态SQL
使⽤用动态 SQL 可简化代码的开发,减少开发者的⼯作量,程序可以⾃动根据业务参数来决定 SQL 的拼接。
1、if 标签
if 标签可以自动根据表达式的结果来决定是否将对应的语句添加到 SQL 中,如果条件不成立则不添加, 如果条件成立则添加。
<select id="findByAccount" parameterType="com.entity.Account" resultType="com.entity.Account">
select * from t_account where 1 = 1
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null and username.size != 0">
and username = #{username}
</if>
<if test="password!=null and password.size != 0">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</select>
2、where 标签
上面 if 标签中的 1=1 是不是看起来很难受?没有办法,它是为了防止SQL出错而存在的。为了解决这个问题,可以使用 where 标签。where 标签可以自动判断是否要删除语句块中的 and 关键字,如果检测到 where 直接跟 and 拼接,则自动删除 and,通常情况下 if 和 where 结合起来使用。
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<if test="id!=0">
id = #{id}
<-- 也可以这样写: and id = #{id} -->
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</where>
</select>
3、choose 、when 标签
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<choose>
<when test="id!=0">
id = #{id}
</when>
<when test="username!=null">
username = #{username}
</when>
<when test="password!=null">
password = #{password}
</when>
<when test="age!=0">
age = #{age}
</when>
</choose>
</where>
</select>
4、trim 标签
trim 标签中的 prefix 和 suffix 属性会被⽤于⽣成实际的 SQL 语句,会和标签内部的语句进行拼接,如果语句前后出现了 prefixOverrides 或者 suffixOverrides 属性中指定的值,MyBatis 框架会⾃动将其删除。
<select id="findByAccount" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<if test="id!=0">
id = #{id}
<-- 这样写也是可以的:and id = #{id} -->
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</trim>
</select>
5、set 标签
set 标签用于 update 操作,会根据参数选择⾃动⽣成 SQL 语句。
<update id="update" parameterType="com.entity.Account">
update t_account
<set>
<if test="username!=null">
username = #{username},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="age!=0">
age = #{age}
</if>
</set>
where id = #{id}
</update>
6、foreach 标签
foreach 标签可以迭代生成⼀系列值,这个标签主要用于 SQL 的 in 语句。
<select id="findByIds" parameterType="com.entity.Account"
resultType="com.entity.Account">
select * from t_account
<where>
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
<select id="queryByIds" resultMap="studentMap" parameterType="map">
select * from t_account
where id in
<foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
#{item}
</foreach>
</select>