Mybatis的xml中使用UPDATE语句无法返回修改行数

/ Java / 0 条评论 / 1210浏览

如下代码。

AccountMapper.java

public interface AccountMapper extends BaseMapper<Account> {
    Integer out(@Param("userId") Long userId, @Param("amount") BigDecimal amount);
}

AccountMapper.xml

<mapper namespace="com.akersman.mapper.AccountMapper">
  <select id="out">
    UPDATE account SET balance = balance - #{amount} WHERE user_id = #{userId}
  </select >
</mapper>

Service里调用

Integer out= accountMapper.out(userId, amount);

这种情况无论UPDATE语句是否执行完修行行数为多少, out始终为null

如何让out的返回值返回数据库修改的行数呢?

只需要将AccountMapper.xml代码中的select标签修改为update

<mapper namespace="com.akersman.mapper.AccountMapper">
  <update id="out">
    UPDATE account SET balance = balance - #{amount} WHERE user_id = #{userId}
  </update>
</mapper>

这样out就能返回正确的修改行数