使用Mybatis-Plus进行单表操作

使用 updateById() 修改数据时,值为null的属性不会被修改。

int updateById(@Param("et") T entity);

 测试代码:

@SpringBootTest
public class SpringBootMybatisPlusTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void test() {
        User user = new User();
        user.setName("yummy");
        user.setId(1L);
        int rows = userMapper.updateById(user);
        System.out.println("rows=" + rows);
    }
}

根据日志输出可知,测试代码实际执行的Sql语句是:UPDATE user SET name='yummy' WHERE id=1。

==>  Preparing: UPDATE user SET name=? WHERE id=?
==> Parameters: yummy(String), 1(Long)
<==    Updates: 1

因此,在设计实体类时,尽量采用包装类来声明属性,以保证不调用setXx()方法时,对象的xx属性值为null。

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

实体类User中, age属性是Integer类型,默认为null。测试类中未调用user.setAge()方法初始化age的值,在执行updateById()方法时不对表中age字段进行修改。

你可能感兴趣的:(Java后端,mybatis,java,数据库)