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);
}
}