在 MyBatis 中,你可以使用 <if>
标签来实现动态更新部分字段的功能,这在只更新有变化的字段时非常有用。
<update id="updateUser" parameterType="User">
UPDATE user
<set>
<if test="username != null">username = #{username},</if>
<if test="password != null">password = #{password},</if>
<if test="email != null">email = #{email},</if>
<if test="phone != null">phone = #{phone}</if>
</set>
WHERE id = #{id}
</update>
<set>
标签:会自动处理 SQL 语句中的逗号,避免在最后一个条件后出现多余的逗号。
<if>
标签:test
属性中的表达式为 true 时,该语句会被包含在 SQL 中。
参数判断:可以判断参数是否为 null 或空字符串等。
<update id="updateUserSelective" parameterType="User">
UPDATE user
<set>
<if test="username != null and username != ''">username = #{username},</if>
<if test="password != null and password.length() > 6">password = #{password},</if>
<if test="email != null and email.contains('@')">email = #{email},</if>
<if test="phone != null and phone.matches('^1[3-9]\\d{9}$')">phone = #{phone}</if>
</set>
WHERE id = #{id}
</update>
MyBatis 使用 OGNL 表达式进行条件判断,支持以下操作:
==
, !=
, <
, <=
, >
, >=
and
, or
, not
或 &&
, ||
, !
contains
, indexOf
, length
, matches
等<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
UPDATE user
<set>
<if test="item.username != null">username = #{item.username},</if>
<if test="item.email != null">email = #{item.email}</if>
</set>
WHERE id = #{item.id}
</foreach>
</update>
<trim>
替代 <set>
以获得更多控制通过这种方式,你可以灵活地只更新那些真正需要更新的字段,提高数据库操作效率。