MybatisPlus--4 更新

updateById

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUpdateById {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * updateById (Entity) 传递的是一个实体
     * 按照实体指定的 id 查询数据,将实体中不为 null 的属性更新
     */
    @Test
    public void testUpdateById() {
        Employee emp = new Employee();
        emp.setUserId(1L);
        emp.setLastName("Rose");
        employeeMapper.updateById(emp);

        Employee employee = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("user_id", 1L));
        System.out.println(employee);
    }
}

update
set

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUpdate {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * update 方法,使用的参数是 实体 和 UpdateWrapper
     * 实体中不为 null 的数据是 set 部分
     * UpdateWrapper 是 where 部分
     */

    @Test
    public void testUpdateWrapper() {
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("last_name", "Jack");
        Employee emp = new Employee();
        emp.setEmail("jj@qq.com");
        emp.setAge(29);
        int rows  = employeeMapper.update(emp, updateWrapper);
        System.out.println(rows);
        // UPDATE employee SET email=?, age=? WHERE last_name = ?

        // UpdateWrapper 也是继承自 AbstractWrapper 和 QueryWrapper 一样,所有 UpdateWrapper
        // 也是可以传递一个实体的,那么实体中不为 null 的属性值将在 where 中
    }

    /**
     * 使用 UpdateWrapper 中的 set 方法设置
     * 这个是对于那种字段值很多,但是需要修改的内容很少的情况下使用,免去创建对象的过程
     */

    @Test
    public void updateByWrapperSet() {
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("last_name", "Jack").set("age", 30);

        // 仅仅使用 updateWrapper 来设置更新
        int rows = employeeMapper.update(null, updateWrapper);
        System.out.println(rows);
    }

    /**
     * LambdaUpdateWrapper
     */
    @Test
    public void updateByWrapperLambda() {
        LambdaUpdateWrapper<Employee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Employee::getLastName, "Jack").set(Employee::getAge, 31);
        int rows = employeeMapper.update(null, lambdaUpdateWrapper);
        System.out.println(rows);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值