记录下MybatisPlus的简单的增删改查
接口概述
Service和Mapper区别
Mapper简化了单表的sql操作步骤(CRUD),而Serivce则是对Mapper的功能增强。
Service虽然加入了数据库的操作,但还是以业务功能为主,而更加复杂的SQL查询,还是要靠Mapper对应的XML文件里去编写SQL语句
常用增删改查
查询所有数据
/**
* 查询所有数据
*/
@GetMapping("/getUserList")
public List<TrainUserEntity> getUserList() {
return trainUserService.list();
}
根据id查询
/**
* 根据id查询数据
*/
@GetMapping("/getUserById")
public TrainUserEntity getUserById(@RequestParam String id) {
return trainUserService.getById(id);
}
根据条件查询
/**
* 使用LambdaQueryWrapper查询指定年龄的人员
*/
@Override
public List<TrainUserEntity> getUserByAge(String age) {
LambdaQueryWrapper<TrainUserEntity> userEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
userEntityLambdaQueryWrapper.eq(TrainUserEntity::getAge, age);
List<TrainUserEntity> list = trainUserMapper.selectList(userEntityLambdaQueryWrapper);
return list;
}
使用xml查询
新增
/**
* 新增
*
* @param trainUserEntity 需要插入的数据
* @return 是否成功
*/
@PostMapping("/saveUser")
public boolean saveUser(@RequestBody TrainUserEntity trainUserEntity) {
return trainService.save(trainUserEntity);
}
/**
* 新增数据
*/
@Override
public boolean add(TrainUserEntity trainUserEntity) {
return trainMapper.add(trainUserEntity);
}
删除
/**
* 根据主键id删除一条数据
*
* @param id 主键id
* @return 是否成功
*/
@PostMapping("/removeById")
public boolean deleteById(@RequestParam String id) {
return trainService.removeById(id);
}
/**
* 根据主键id删除一条数据
*
* @param id 主键id
* @return 删除数据的条数
*/
@Override
public int deleteById(String id) {
LambdaQueryWrapper<TrainUserEntity> userEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
userEntityLambdaQueryWrapper.eq(TrainUserEntity::getId, id);
int result = trainMapper.delete(userEntityLambdaQueryWrapper);
return result;
}
修改
/**
* id修改一条数据
*
* @param trainUserEntity 需要修改的数据
* @return 修改结果
*/
@PostMapping("/updateUser")
public boolean updateUser(@RequestBody TrainUserEntity trainUserEntity) {
return trainService.updateById(trainUserEntity);
}
/**
* 根据id更新实体数据
*/
@Override
public int modifyById(TrainUserEntity trainUserEntity) {
LambdaUpdateWrapper<TrainUserEntity> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(TrainUserEntity::getId, trainUserEntity.getId())
.set(TrainUserEntity::getName, trainUserEntity.getName())
.set(TrainUserEntity::getAddress, trainUserEntity.getAddress());
int result = trainMapper.update(null, updateWrapper);
return result;
}