苍穹外卖学习笔记(二)

一.新增员工

  1. 编写新增员工接口设计的 DTO
    20240907180037
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.sky.dto;

import lombok.Data;

import java.io.Serializable;

@Data
public class EmployeeDTO implements Serializable {

private Long id;

private String username;

private String name;

private String phone;

private String sex;

private String idNumber;

}
  1. controller
1
2
3
4
5
6
7
8
9
10
11
12
/**
* 新增员工
*
* @return
*/
@PostMapping
@ApiOperation("新增员工")
public Result save(@RequestBody EmployeeDTO employeeDTO) {
log.info("新增员工:{}", employeeDTO);
employeeService.save(employeeDTO);
return Result.success();
}
  1. service
1
2
3
4
5
6
/**
* 添加员工
* @param employeeDTO
* @return
*/
void save(@RequestBody EmployeeDTO employeeDTO);
  1. serviceimpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 添加员工
*
* @param employeeDTO
* @return
*/
@Override
public void save(EmployeeDTO employeeDTO) {
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee);
employee.setStatus(StatusConstant.ENABLE);//默认启用
//生成盐
byte[] salt = new byte[SALT_LENGTH];
RANDOM.nextBytes(salt);
employee.setSalt(Base64.getEncoder().encodeToString(salt));
//对密码进行加密,默认密码为123456
String password = hashPassword(PasswordConstant.DEFAULT_PASSWORD, employee.getSalt());
employee.setPassword(password);
//设置创建时间和更新时间
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
//设置创建人和更新人
//XJJ TODD 2024/9/7:后期需要修改
employee.setCreateUser(10L);
employee.setUpdateUser(10L);
employeeMapper.insert(employee);
}

由于我这里将 Mybatis 换成了 Mybatis-plus,所以 Mybatis 相关的代码不再描写

  1. 引入依赖
1
2
3
4
5
6
<!-- mybatisPlus 核心库 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
  1. 修改 application.yml 配置文件
1
2
3
4
5
6
7
# mybatis-plus配置
mybatis-plus:
configuration:
# 驼峰命名
map-underscore-to-camel-case: true
# 日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  1. 修改 employee 实体类,添加 ID 自动增长策略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.sky.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("employee")
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;

@TableId(value = "id", type = IdType.AUTO)
private Long id;

private String username;

private String name;

private String password;

private String phone;

private String sex;

private String idNumber;

private Integer status;

//@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;

//@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;

private Long createUser;

private Long updateUser;

private String salt;

}
  1. 删除 resource 下的 mapper 包,将 server 中的 mapper 包改为继承自 BaseMapper
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.sky.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sky.dto.EmployeeDTO;
import com.sky.entity.Employee;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {

}
  1. 修改启动类,增加 mapper 扫描区间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.sky;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@MapperScan("com.sky.mapper") //扫描mapper接口
@Slf4j
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}

二.员工分页查询

  1. 编写分页查询接口的 DTO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.sky.dto;

import lombok.Data;

import java.io.Serializable;

@Data
public class EmployeePageQueryDTO implements Serializable {

//员工姓名
private String name;

//页码
private int page;

//每页显示记录数
private int pageSize;

}
  1. controller
1
2
3
4
5
6
7
@GetMapping("/page")
@ApiOperation("分页查询员工")
public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) {
log.info("分页查询员工:{}", employeePageQueryDTO);
employeeService.page(employeePageQueryDTO);
return Result.success();
}
  1. service
1
2
3
4
5
6
/**
* 分页查询员工
* @param employeePageQueryDTO
* @return
*/
PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO);
  1. serviceimpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Transactional
@Override
public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
// 创建分页对象
Page<Employee> page = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
// 创建查询条件
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
// 排除姓名为null的记录
queryWrapper.isNotNull(Employee::getName);
// 使用like方法进行模糊查询,参数化防止SQL注入
if (StringUtils.isNotBlank(employeePageQueryDTO.getName())) {
queryWrapper.like(Employee::getName, employeePageQueryDTO.getName());
}
// 根据创建时间降序排序
queryWrapper.orderByDesc(Employee::getCreateTime);
// 执行分页查询
Page<Employee> employeePage = employeeMapper.selectPage(page, queryWrapper);
// 提取结果
long total = employeePage.getTotal();
List<Employee> records = employeePage.getRecords();
// 返回结果
return new PageResult(total, records);
}

注意:使用 MP 分页时不要配置 MP 分页插件,否则会找不到对象(Mapper)

三.启用禁用员工账号

  1. controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 修改员工状态
*
* @param id
* @param status
* @return
*/
@PostMapping("/status/{status}")
@ApiOperation("修改员工状态")
public Result startOrStop(Long id, @PathVariable Integer status) {
log.info("修改员工状态:id={},status={}", id, status);
employeeService.startOrStop(id, status);
return Result.success();
}
  1. service
1
2
3
4
5
6
/**
* 修改员工状态
* @param
* @return
*/
void startOrStop(Long id, Integer status);
  1. impl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   /**
* 修改员工状态
*
* @param id
* @param status
* @return
*/
@Override
public void startOrStop(Long id, Integer status) {
// Employee employee = new Employee();
// employee.setId(id);
// employee.setStatus(status);
// employee.setUpdateTime(LocalDateTime.now());
// employee.setUpdateUser(BaseContext.getCurrentId());
Employee employee = Employee.builder()
.id(id)
.status(status)
.updateTime(LocalDateTime.now())
.updateUser(BaseContext.getCurrentId())
.build();
employeeMapper.updateById(employee);
}

四.编辑员工

  1. controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 根据id查询员工
*
* @param id
* @return
*/
@GetMapping("/{id}")
@ApiOperation("根据id查询员工")
public Result<Employee> getById(@PathVariable Long id) {
log.info("根据id查询员工:id={}", id);
Employee employee = employeeService.getById(id);
return Result.success(employee);
}

/**
* 修改员工
*
* @param employeeDTO
*/
@PutMapping()
@ApiOperation("修改员工")
public Result update(@RequestBody EmployeeDTO employeeDTO) {
log.info("修改员工:{}", employeeDTO);
employeeService.update(employeeDTO);
return Result.success();
}
  1. service
1
2
3
4
5
6
7
8
9
10
11
12
/**
* 根据id查询员工
* @param id
* @return
*/
Employee getById(Long id);

/**
* 修改员工
* @param employeeDTO
*/
void update(EmployeeDTO employeeDTO);
  1. impl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 根据id查询员工
*
* @param id
* @return
*/
@Override
public Employee getById(Long id) {
Employee employee = employeeMapper.selectById(id);
employee.setPassword("********");
return employee;
}

/**
* 修改员工
*
* @param employeeDTO
*/
@Override
public void update(EmployeeDTO employeeDTO) {
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee);
employee.setUpdateTime(LocalDateTime.now());
employee.setUpdateUser(BaseContext.getCurrentId());
employeeMapper.updateById(employee);
}

五.导入分类模块功能代码

最后的分类管理接口已经在分类分页查询中内置,可以删掉,好吧,后面添加菜品需要这个接口,不可以删掉

  1. controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.sky.controller.admin;

import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/category")
@Slf4j
@Api(tags = "分类管理")
public class CategoryController {

@Autowired
private CategoryService categoryService;

/**
* 添加分类
*/
@PostMapping
@ApiOperation("添加分类")
public Result<String> saveCategory(@RequestBody CategoryDTO categoryDTO) {
log.info("添加分类:{}", categoryDTO);
categoryService.saveCategory(categoryDTO);
return Result.success();
}

/**
* 分类分页查询
*/
@GetMapping("/page")
@ApiOperation("分类分页查询")
public Result<PageResult> pageCategory(CategoryPageQueryDTO categoryPageQueryDTO) {
log.info("分类分页查询:{}", categoryPageQueryDTO);
PageResult pageResult = categoryService.pageCategory(categoryPageQueryDTO);
return Result.success(pageResult);
}

/**
* 修改分类状态
*/
@PostMapping("/status/{status}")
@ApiOperation("修改分类状态")
public Result<String> updateCategoryStatus(@PathVariable("status") Integer status, Long id) {
log.info("修改分类状态:status={}, id={}", status, id);
categoryService.updateCategoryStatus(status, id);
return Result.success();
}

/**
* 删除分类
*/
@DeleteMapping
@ApiOperation("根据id删除分类")
public Result<String> deleteCategory(Long id) {
log.info("删除分类:id={}", id);
categoryService.deleteCategory(id);
return Result.success();
}

/**
* 修改分类
*/
@PutMapping
@ApiOperation("修改分类")
public Result updateCategory(@RequestBody CategoryDTO categoryDTO) {
log.info("修改分类:{}", categoryDTO);
categoryService.updateCategory(categoryDTO);
return Result.success();
}

/**
* 分类列表
*/
@GetMapping("/list")
@ApiOperation("根据类型查询分类")
public Result<List<Category>> listCategory(Integer type) {
log.info("根据类型查询分类:type={}", type);
List<Category> list = categoryService.listCategory(type);
return Result.success(list);
}
}

  1. service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.sky.service;

import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.result.PageResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

public interface CategoryService {

/**
* 添加分类
*/
void saveCategory(@RequestBody CategoryDTO categoryDTO);

/**
* 分类分页查询
*/
PageResult pageCategory(CategoryPageQueryDTO categoryPageQueryDTO);

/**
* 修改分类状态
*/
void updateCategoryStatus(Integer status, Long id);

/**
* 删除分类
*/
void deleteCategory(Long id);

/**
* 修改分类
*/
void updateCategory(CategoryDTO categoryDTO);

/**
* 分类列表
*/
List<Category> listCategory(@Param("type") Integer type);
}

  1. impl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Employee;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

@Autowired
private CategoryMapper categoryMapper;

/**
* 添加分类
*/
@Transactional
@Override
public void saveCategory(CategoryDTO categoryDTO) {
// Category category = new Category();
// BeanUtils.copyProperties(categoryDTO, category);
// 使用建造者模式
Category category = Category.builder()
.name(categoryDTO.getName())
.id(categoryDTO.getId())
.sort(categoryDTO.getSort())
.type(categoryDTO.getType())
.build();
// 设置默认值
category.setStatus(StatusConstant.DISABLE);
// category.setCreateTime(LocalDateTime.now());
// category.setUpdateTime(LocalDateTime.now());
// category.setCreateUser(BaseContext.getCurrentId());
// category.setUpdateUser(BaseContext.getCurrentId());
log.info("添加分类:{}", category);
categoryMapper.insert(category);
}

/**
* 分类分页查询
*/
@Transactional
@Override
public PageResult pageCategory(CategoryPageQueryDTO categoryPageQueryDTO) {
//创建分页对象
Page<Category> page = new Page<>(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
//查询条件
LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
// 如果 type 不为 null,则添加 type 的过滤条件
if (categoryPageQueryDTO.getType() != null) {
queryWrapper.eq(Category::getType, categoryPageQueryDTO.getType());
}
//模糊查询
queryWrapper.isNotNull(Category::getName);
//参数化防止SQL注入
if (StringUtils.isNotBlank(categoryPageQueryDTO.getName())) {
queryWrapper.like(Category::getName, categoryPageQueryDTO.getName());
}
//排序
queryWrapper.orderByDesc(Category::getSort);
//分页查询
Page<Category> categoryPage = categoryMapper.selectPage(page, queryWrapper);
long total = categoryPage.getTotal();
List<Category> records = categoryPage.getRecords();
return new PageResult(total, records);
}

/**
* 修改分类状态
*/
@Override
public void updateCategoryStatus(Integer status, Long id) {
Category build = Category.builder()
.id(id)
.status(status)
.updateTime(LocalDateTime.now())
.updateUser(BaseContext.getCurrentId())
.build();
categoryMapper.updateById(build);
}

/**
* 删除分类
*/
@Override
public void deleteCategory(Long id) {
categoryMapper.deleteById(id);
}

/**
* 修改分类
*/
@Override
public void updateCategory(CategoryDTO categoryDTO) {
Category build = Category.builder()
.id(categoryDTO.getId())
.name(categoryDTO.getName())
.sort(categoryDTO.getSort())
.type(categoryDTO.getType())
.updateTime(LocalDateTime.now())
.updateUser(BaseContext.getCurrentId())
.build();
categoryMapper.updateById(build);
}

/**
* 分类列表
*/
@Override
public List<Category> listCategory(Integer type) {
LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
boolean flag = type != null;
queryWrapper.eq(flag, Category::getType, type)
.eq(Category::getStatus, StatusConstant.ENABLE)
.orderByAsc(Category::getSort)
.orderByDesc(Category::getCreateTime);
List<Category> categories = categoryMapper.selectList(queryWrapper);
log.info("分类列表:{}", categories);
return categories;
}
}

  1. mapper
1
2
3
4
@Mapper
public interface CategoryMapper extends BaseMapper<Category> {

}