MyBatis Plus Service CRUD接口测试
Service如何集成MP
@Mapper
public interface RoleMapper extends BaseMapper<RoleDO> {
}
public interface RoleService extends IService<RoleDO>{
}
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleDO> implements RoleService{
}
插入
插入一条记录
boolean save(T entity)
批量插入
boolean saveBatch(Collection<T> entityList)
批量插入(默认一次插入多少)
boolean saveBatch(Collection<T> entityList, int batchSize);
更新
根据ID更新,null值的属性不参与更新
Employee employee = new Employee();
employee.setId(7);
employee.setLastName("a");
employee.setAge(23);
employee.setEmail(null);
employee.setGender(null);
service.updateById(employee);
UPDATE tb_employee SET last_name='a', age=23
WHERE id=7;
根据条件进行更新,并置空其他属性(项目库的我那个头疼的置空功能就能用这个解决)。
RoleDO roleDO = new RoleDO(roleDto);
roleService.update(roleDO, new UpdateWrapper<RoleDO>().lambda().
eq(RoleDO::getId, roleDO.getId())
//如果要置空其他的属性
.set(RoleDO::getUpdateId, null)
.set(RoleDO::getUpdateTime, null)
);
查询
根据ID获取
T getById(Serializable id)
获取一个(如果出现多个,则报错,传统的Excepted One , Actual Two 异常)
roleService.getOne(new QueryWrapper<RoleDO>().lambda()
.eq(RoleDO::getIsManager, role.getIsManager())
);
获取一个(如果出现多个,获取一个)
roleService.getOne(new QueryWrapper<RoleDO>().lambda()
.eq(RoleDO::getIsManager, role.getIsManager()), false
);
删除
根据主键ID
boolean removeById(Serializable id)
根据多个主键ID
boolean removeByIds(Collection<? extends Serializable> idList)
根据条件进行删除
RoleDO roleDO = new RoleDO(roleDto);
roleService.remove(new QueryWrapper<RoleDO>().lambda().
eq(RoleDO::getId, roleDO.getId())
);
通过Map拼接条件删除
Map<String, Object> map = new HashMap<>();
map.put("id", roleDO.getId());
map.put("role_name", roleDO.getRoleName());
roleService.removeByMap(map);
where id = #{id} AND role_name = #{roleName}
批量查询
查询所有
List<T> list()
根据ID批量查询
List<T> listByIds(Collection<? extends Serializable> idList)
根据条件批量查询
RoleDO roleDO = new RoleDO(dto);
return roleService.list(new QueryWrapper<RoleDO>().lambda()
.eq(RoleDO::getIsManager, roleDO.getIsManager())
);
分页查询
pageIndex第几页,pageSize每页几条数据
Page page = new Page(pageIndex,pageSize);
return roleService.page(page);
根据条件分页查询
@GetMapping(value = "/pageByWrap")
@SuppressWarnings(value = "unchecked")
public Object pageByWrap() {
return roleService.page(PageContext.getPage(), new QueryWrapper<RoleDO>().lambda()
.eq(RoleDO::getIsManager, "0")
);
}
查个数数量
查询所有,总记录数
int count()
根据条件,查询总记录数
return roleService.count(new QueryWrapper<RoleDO>().lambda()
.eq(RoleDO::getIsManager, "0")
);