启用禁用员工
Controller
路径参数前面加上@Path~注解来获取参数
@PostMapping("/status/{status}") @ApiOperation("启用禁用员工") public Result StartOrStop(@PathVariable("status") Integer status, Long id){ log.info("启用禁用"); employeeService.StartOrStop(status,id); return Result.success(); }
Service
创建一个完整的类方便mapper插入数据.用于层之间交换数据方便
使用builder需要加上@builder注解在原类上,然后可以通过以下方式快速构建对象
@Override public void StartOrStop(Integer status, Long id) { Employee employee = Employee.builder().status(status).id(id).build(); employeeMapper.update(employee); }
Mapper
使用动态sql
id="update"意思是将这段sql代码取名为update,这样以后可以直接以这个名字来调用
parameterType="Employee"是指明,这个sql的传入参数是Emp格式,下面set的参数都会从中获取
使用<if>标签也可以防止sql注入
<update id="update" parameterType="Employee"> update employee <set> <if test ="name != null">name = #{name},</if> </set > where id = #{id} </update>
员工分页查询
Controller
使用Dto类方便前端页面传入的数据和Controller层交互
返回值使用Result.success中,可以返回Object类型的方法直接返回结果
pageResult类含有: 数据条数/数据集合
@GetMapping("/page") @ApiOperation("员工分页查询") public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){ log.info("员工分页查询,参数为{}",employeePageQueryDTO); PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO); return Result.success(pageResult); }
Service
使用分页查询插件(PageHelper),传入页码和每页记录数
这里的page<>中填入你的查询类,page是插件中自带的类,可以从中获取总记录数和结果,再封装到PageResult返回
@Override public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) { PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize()); Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO); long total = page.getTotal(); List<Employee> records = page.getResult(); return new PageResult(total,records); } }
Mapper
resultType规定了数据结果的格式
<select id="pageQuery" resultType="com.sky.entity.Employee"> select * from employee <where> <if test="name != null and name !=''"> and name like concat('%',#{name},'%') </if> </where> </select>
编辑员工
Controller
路径参数使用@PathVariable来接收
@GetMapping("/{id}") @ApiOperation("查询员工信息") public Result<Employee> select(@PathVariable Long id){ log.info("查询员工信息"); Employee employee = employeeService.select(id); return Result.success(employee); } @PutMapping @ApiOperation("修改员工") public Result update(@RequestBody EmployeeDTO employeeDTO){ log.info("修改员工"); employeeService.update(employeeDTO); return Result.success(); }
Service
update此时使用的是employee而非DTO,这时候需要用到对象拷贝
BeanUtils.copyProperties(employeeDTO,employee);
new一个employee, 然后把属性拷贝到里面去
@Override public Employee select(Long id) { return employeeMapper.select(id); } @Override public void update(EmployeeDTO employeeDTO) { Employee employee = new Employee(); BeanUtils.copyProperties(employeeDTO,employee); employeeMapper.update(employee); }
Mapper
@Select("select * from employee where id = #{id}") Employee select(Long id); void update(Employee employeeDTO);