当使用带有 <set> 的 mybatis 时,所有测试都失败时是否可以跳过更新?

Is it possible to skip update when all tests failed when using mybatis with <set>?

在使用mybatis的时候,动态SQL非常强大,比如一个UPDATE:

<update id="update">
  UPDATE BOOKS
  <set>
    <if test="book.author != null">AUTHOR=#{book.author},</if>
    <if test="book.name != null">NAME=#{book.name}</if>
  </set>
  WHERE ID=#{book.id}
</update>

当 author 或 name 不为 null 时这有效,当两者都为 null 时失败,因为 SQL 有语法错误。

我的问题:当 <set> 之间的所有测试都失败时是否可以跳过更新,或者我必须编写额外的 java 代码以在执行 update 语句之前进行检查?

无法使用 XML 元素跳过语句执行。

如果您只是想避免编写 Java 条件,但是,在 SET 子句中包含 ID 可能就足够了。

UPDATE BOOKS
SET
  ID = #{book.id}
  <if test="book.author != null">, AUTHOR=#{book.author}</if>
  <if test="book.name != null">, NAME=#{book.name}</if>
WHERE ID = #{book.id}