Mabatis update 无数据修改更新返回1

3,654 阅读2分钟

问题描述

假设有一个user表,包含user_name、user_password字段,执行update函数,返回1还是0,返回值代表影响行数还是其他呢?

update 方法

@Update("update user set user_password = #{password} where user_name = #{userName}")
int updateByUserName(@Param("userName") String userName, @Param("password") String password);

数据库初始记录

连接配置

server:
  port: 9099

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root

mybatis:
  configuration:
    # 数据表、java类 驼峰、下划线命名转换
    map-underscore-to-camel-case: true

logging:
  level:
    # 日志打印级别,可具体到包、类,可显示具体执行的sql语句
    com.kk.mapper: debug

单元测试类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testUpdateUser() {
        String userName = "kk";
        String password = "abc123";
        int result = userMapper.updateByUserName(userName, password);
        Assert.assertSame("更新测试",0, result);
    }
}

测试

第一个测试

根据username更新password,把password由”123456“更新成”abc123“,如果返回值是影响函数的话,应该返回\color{red}{1},实际也是返回\color{red}{1},单元测试通过

单元测试通过,观察到数据库中的记录也发生了变化

单元测试通过且数据库中记录也更新成功,说明mybatis的update返回值是受影响的行数 有待继续 确认

第二个测试

在终端中直接执行update语句受影响行数确实0

继续执行刚才的单元测试,发现执行成功,console中显示的update return值也是\color{red}{1},和期望的不一致,因此mybatis的update返回值是并不是受影响的行数

解决方案

是否有方法可以使mybatis的update返回受影响行数呢?答案是肯定有的,并且很简单。 只需要修改数据库链接的配置即可:\color{red}{useAffectedRows=true}

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useAffectedRows=true

再次执行单元测试,返回结果变成\color{red}{0}