2. 员工AND分类模块完善
2.1 新增员工
2.1.1 需求分析设计
接口设计
本项目约定:
管理端发出的请求,统一使用 /admin 作为前缀
用户端发出的请求,统一使用 /user 作为前缀
数据库设计(employee表):
2.1.2 代码开发
注意:当前端提交的数据和实体类中对应的属性差别比较大时,建议使用DTO来封装数据
在EmployeeController中创建新增员工方法,接收前端提交的参数
/** * 新增员工 * @param employeeDTO * @return */ @ApiOperation("新增员工") @PostMapping public Result<String> save(@RequestBody EmployeeDTO employeeDTO) { employeeService.saveEmp(employeeDTO); return Result.success(); }
**注:**Result类定义了后端统一返回结果格式。
进入sky-common模块,在com.sky.result包下定义了Result.java
package com.sky.result; import lombok.Data; import java.io.Serializable; /** * 后端统一返回结果 * @param <T> */ @Data public class Result<T> implements Serializable { private Integer code; //编码:1成功,0和其它数字为失败 private String msg; //错误信息 private T data; //数据 public static <T> Result<T> success() { Result<T> result = new Result<T>(); result.code = 1; return result; } public static <T> Result<T> success(T object) { Result<T> result = new Result<T>(); result.data = object; result.code = 1; return result; } public static <T> Result<T> error(String msg) { Result result = new Result(); result.msg = msg; result.code = 0; return result; } }
在EmployeeService接口中声明新增员工方法
/** * 新增员工 * @param employeeDTO * @return */ void saveEmp(EmployeeDTO employeeDTO);
在sky-common模块com.sky.constants包下已定义StatusConstant.java
package com.sky.constant; /** * 状态常量,启用或者禁用 */ public class StatusConstant { //启用 public static final Integer ENABLE = 1; //禁用 public static final Integer DISABLE = 0; }
在EmployeeServiceImpl中实现新增员工方法
/** * 新增员工 * @param employeeDTO */ @Override public void saveEmp(EmployeeDTO employeeDTO) { //1.创建数据库中员工表对照对象 Employee employee = new Employee(); //TODO 校验保存员工信息是否合法 String phone = employeeDTO.getPhone(); String idNumber = employeeDTO.getIdNumber(); //2.使用spring框架对象拷贝:保证源和目标属性名相同 BeanUtils.copyProperties(employeeDTO,employee); //3.添加其他未设置项 //设置员工状态 默认正常状态 1表示正常 0表示锁定 employee.setStatus(StatusConstant.ENABLE); //设置密码 employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes())); //设置创建时间 employee.setCreateTime(LocalDateTime.now()); //设置更新时间 employee.setUpdateTime(LocalDateTime.now()); //设置创建人 employee.setCreateUser(BaseContext.getCurrentId()); //设置修改人 employee.setUpdateUser(BaseContext.getCurrentId()); employeeMapper.insertEmp(employee); }
其中设置员工id
BaseContext.getCurrentId()
为com.sky.interceptor.JwtTokenAdminInterceptor
中进行JWT令牌解析得到的登录员工ID,通过BaseContext.setCurrentId(empId)
完成设置。package com.sky.interceptor; import com.sky.constant.JwtClaimsConstant; import com.sky.context.BaseContext; import com.sky.properties.JwtProperties; import com.sky.utils.JwtUtil; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * jwt令牌校验的拦截器 */ @Component @Slf4j public class JwtTokenAdminInterceptor implements HandlerInterceptor { @Autowired private JwtProperties jwtProperties; /** * 校验jwt * * @param request * @param response * @param handler * @return * @throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断当前拦截到的是Controller的方法还是其他资源 if (!(handler instanceof HandlerMethod)) { //当前拦截到的不是动态方法,直接放行 return true; } //1、从请求头中获取令牌 String token = request.getHeader(jwtProperties.getAdminTokenName()); //2、校验令牌 try { log.info("jwt校验:{}", token); Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token); Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString()); log.info("当前员工id:", empId); //将当前id存储到当前线程中 BaseContext.setCurrentId(empId); //3、通过,放行 return true; } catch (Exception ex) { //4、不通过,响应401状态码 response.setStatus(401); return false; } } }
其中
JwtProperties
部分代码如下
在EmployeeMapper中声明insert方法
/** * 新增员工 * @param employee */ @Insert("insert into employee(name, username, password, phone, sex, id_number, create_time, update_time, " + "create_user, update_user,status) " + "values(" + "#{name},#{username},#{password},#{phone},#{sex},#{idNumber},#{createTime},#{updateTime}," + "#{createUser},#{updateUser},#{status})") void insertEmp(Employee employee);
2.1.3 功能测试
功能测试方式:
通过接口文档测试
通过前后端联调测试
注意:由于开发阶段前端和后端是并行开发的,后端完成某个功能后,此时前端对应的功能可能还没有开发完成,导致无法进行前后端联调测试。所以在开发阶段,后端测试主要以接口文档测试为主。
通过
前面通过
admin-ttl: 7200000
设置了jwt
令牌过期时间为2小时,可将admin-ttl
时间设置长一点生成一个token保存在knife4j
的接口文档测试全局参数中中,报401为token过期造成的。
添加令牌:
将合法的JWT令牌添加到全局参数中
文档管理–>全局参数设置–>添加参数
2.1.4 代码完善
通过某种方式动态获取当前登录员工的id。
员工登录成功后会生成JWT令牌并响应给前端,后续请求中,前端会携带JWT令牌,通过JWT令牌可以解析出当前登录员工id
ThreadLocal
介绍:
ThreadLocal 并不是一个Thread,而是Thread的局部变量。
ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。常用方法:
- public void set(T value) 设置当前线程的线程局部变量的值
- public T get() 返回当前线程所对应的线程局部变量的值
- public void remove() 移除当前线程的线程局部变量
在单线程的模型下:ThreadLocal能够在线程内部完成数据的共享. 在多线程的模型下:ThreadLocal能够解决多个线程并行,争抢资源,造成的线程安全问题.
在sky-common模块中已经封装了 ThreadLocal 操作的工具类:
package com.sky.context; public class BaseContext { public static ThreadLocal<Long> threadLocal = new ThreadLocal<>(); public static void setCurrentId(Long id) { threadLocal.set(id); } public static Long getCurrentId() { return threadLocal.get(); } public static void removeCurrentId() { threadLocal.remove(); } }
2.1.5 代码提交
后续代码提交都省略,只保留标题部分。
2.2 员工分页查询
2.2.1 需求分析和设计
产品原型
业务规则:
- 根据页码展示员工信息
- 每页展示10条数据
- 分页查询时可以根据需要,输入员工姓名进行查询
接口设计
注意事项:
- 请求参数类型为Query,不是json格式提交,在路径后直接拼接。/admin/employee/page?name=zhangsan
- 返回数据中records数组中使用Employee实体类对属性进行封装。
2.2.2 代码开发
设计DTO类
根据请求参数进行封装,在sky-pojo模块中
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; }
封装PageResult
后面所有的分页查询,统一都封装为PageResult对象。
在sky-common模块
package com.sky.result; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; /** * 封装分页查询结果 */ @Data @AllArgsConstructor @NoArgsConstructor public class PageResult implements Serializable { private long total; //总记录数 private List records; //当前页数据集合 }
员工信息分页查询后端返回的对象类型为: Result
package com.sky.result; import lombok.Data; import java.io.Serializable; /** * 后端统一返回结果 * @param <T> */ @Data public class Result<T> implements Serializable { private Integer code; //编码:1成功,0和其它数字为失败 private String msg; //错误信息 private T data; //数据 public static <T> Result<T> success() { Result<T> result = new Result<T>(); result.code = 1; return result; } public static <T> Result<T> success(T object) { Result<T> result = new Result<T>(); result.data = object; result.code = 1; return result; } public static <T> Result<T> error(String msg) { Result result = new Result(); result.msg = msg; result.code = 0; return result; } }
Controller层
在sky-server模块中,com.sky.controller.admin.EmployeeController中添加分页查询方法。
/** * 员工分页查询 * @param employeePageQueryDTO * @return */ @GetMapping("/page") @ApiOperation("员工分页查询") public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){ log.info("员工分页查询,参数为:{}", employeePageQueryDTO); PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);//后续定义 return Result.success(pageResult); }
Service层接口
在EmployeeService接口中声明pageQuery方法:
/** * 分页查询 * @param employeePageQueryDTO * @return */ PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO);
Service层实现类
在EmployeeServiceImpl中实现pageQuery方法:
/** * 分页查询 * * @param employeePageQueryDTO * @return */ public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) { // select * from employee limit 0,10 //开始分页查询 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); }
**注意:**此处使用 mybatis 的分页插件 PageHelper 来简化分页代码的开发。底层基于 mybatis 的拦截器实现。
故在pom.xml文中添加依赖(初始工程已添加)
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>${pagehelper}</version> </dependency>
Mapper层
在 EmployeeMapper 中声明 pageQuery 方法:
/** * 分页查询 * @param employeePageQueryDTO * @return */ Page<Employee> pageQuery(EmployeePageQueryDTO employeePageQueryDTO);
在 src/main/resources/mapper/EmployeeMapper.xml 中编写SQL:
<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> order by create_time desc </select>
2.2.3 功能测试
可以通过接口文档进行测试,也可以进行前后端联调测试。
接下来使用两种方式分别测试:
接口文档测试
**重启服务:**访问http://localhost:8080/doc.html,进入员工分页查询
响应结果:
前后端联调测试
点击员工管理
输入员工姓名为zhangsan
可见最后操作时间格式不清晰,为连串格式的。
2.2.4 代码完善
**问题描述:**操作时间字段显示有问题。
解决方式:
1). 方式一
在属性上加上注解,对日期进行格式化
但这种方式,需要在每个时间属性上都要加上该注解,使用较麻烦,不能全局处理。
2). 方式二(推荐 )
在WebMvcConfiguration中扩展SpringMVC的消息转换器,统一对日期类型进行格式处理
/** * 扩展Spring MVC框架的消息转化器 * @param converters */ protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) { log.info("扩展消息转换器..."); //创建一个消息转换器对象 MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); //需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据 converter.setObjectMapper(new JacksonObjectMapper()); //将自己的消息转化器加入容器中 converters.add(0,converter); }
添加后,再次测试
时间格式定义,sky-common模块中
package com.sky.json; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; /** * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象] * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON] */ public class JacksonObjectMapper extends ObjectMapper { public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; //public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm"; public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; public JacksonObjectMapper() { super(); //收到未知属性时不报异常 this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); //反序列化时,属性不存在的兼容处理 this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); SimpleModule simpleModule = new SimpleModule() .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))) .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))) .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT))) .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))) .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))) .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT))); //注册功能模块 例如,可以添加自定义序列化器和反序列化器 this.registerModule(simpleModule); } }
2.2.5 代码提交
和新增员工代码提交一致,不再赘述。
2.3 启用禁用员工账号
2.3.1 需求分析与设计
产品原型
在员工管理列表页面,可以对某个员工账号进行启用或者禁用操作。账号禁用的员工不能登录系统,启用后的员工可以正常登录。如果某个员工账号状态为正常,则按钮显示为 “禁用”,如果员工账号状态为已禁用,则按钮显示为"启用"。
启禁用员工原型:
业务规则:
- 可以对状态为“启用” 的员工账号进行“禁用”操作
- 可以对状态为“禁用”的员工账号进行“启用”操作
- 状态为“禁用”的员工账号不能登录系统
接口设计
1). 路径参数携带状态值。
2). 同时,把id传递过去,明确对哪个用户进行操作。
3). 返回数据code状态是必须,其它是非必须。
2.3.2 代码开发
Controller层
在sky-server模块中,根据接口设计中的请求参数形式对应的在 EmployeeController 中创建启用禁用员工账号的方法:
/** * 启用禁用员工账号 * @param status * @param id * @return */ @PostMapping("/status/{status}") @ApiOperation("启用禁用员工账号") public Result startOrStop(@PathVariable Integer status,Long id){ log.info("启用禁用员工账号:{},{}",status,id); employeeService.startOrStop(status,id);//后绪步骤定义 return Result.success(); }
Service层接口
在 EmployeeService 接口中声明启用禁用员工账号的业务方法:
/** * 启用禁用员工账号 * @param status * @param id */ void startOrStop(Integer status, Long id);
Service层实现类
在 EmployeeServiceImpl 中实现启用禁用员工账号的业务方法:
/** * 启用禁用员工账号 * * @param status * @param id */ public void startOrStop(Integer status, Long id) { Employee employee = Employee.builder() .status(status) .id(id) .build(); employeeMapper.update(employee); }
Mapper层
在 EmployeeMapper 接口中声明 update 方法:
/** * 根据主键动态修改属性 * @param employee */ void update(Employee employee);
在 EmployeeMapper.xml 中编写SQL:
<update id="update" parameterType="Employee"> update employee <set> <if test="name != null">name = #{name},</if> <if test="username != null">username = #{username},</if> <if test="password != null">password = #{password},</if> <if test="phone != null">phone = #{phone},</if> <if test="sex != null">sex = #{sex},</if> <if test="idNumber != null">id_Number = #{idNumber},</if> <if test="updateTime != null">update_Time = #{updateTime},</if> <if test="updateUser != null">update_User = #{updateUser},</if> <if test="status != null and status != '' or status == 0">status = #{status},</if> </set> where id = #{id} </update>
**注意:**若xml中只写
status != null and status != ''
当status为0时,因为status为Integer类型的。数字类型字段设置为0时,sql没有被拼接。原因如下,进源码查看:
public abstract class OgnlOps implements NumericTypes { //省略其他无用代码 public static double doubleValue(Object value) throws NumberFormatException { if (value == null) { return 0.0D; } else { Class c = value.getClass(); if (c.getSuperclass() == Number.class) { return ((Number)value).doubleValue(); } else if (c == Boolean.class) { return (Boolean)value ? 1.0D : 0.0D; } else if (c == Character.class) { return (double)(Character)value; } else { String s = stringValue(value, true); //这个位置会把’‘空串处理成0 return s.length() == 0 ? 0.0D : Double.parseDouble(s); } } } }
最后一段代码,会把
''
转换成0.0D
,if判断就变成了status != null and status != 0
,所以当把status设置为0时,结果就变成了false,导致sql不会进行拼接,更新status数据失败。
2.3.3 功能测试
接口文档测试
**测试前,**查询employee表中员工账号状态
开始测试
测试完毕后,再次查询员工账号状态
前后端联调测试
测试前:
点击禁用:
2.3.4 代码提交
提交—描述—推送
2.4 编辑员工
2.4.1 需求分析与设计
产品原型
在员工管理列表页面点击 “编辑” 按钮,跳转到编辑页面,在编辑页面回显员工信息并进行修改,最后点击 “保存” 按钮完成编辑操作。
员工列表原型:
修改页面原型:
注:点击修改时,数据应该正常回显到修改页面。
接口设计
根据上述原型图分析,编辑员工功能涉及到两个接口:
- 根据id查询员工信息
- 编辑员工信息
1). 根据id查询员工信息
2). 编辑员工信息
注:因为是修改功能,请求方式可设置为PUT。
2.4.2 代码开发
回显员工信息功能
1). Controller层
在 EmployeeController 中创建 getById 方法:
/** * 根据id查询员工信息 * @param id * @return */ @GetMapping("/{id}") @ApiOperation("根据id查询员工信息") public Result<Employee> getById(@PathVariable Long id){ Employee employee = employeeService.getById(id); return Result.success(employee); }
2). Service层接口
在 EmployeeService 接口中声明 getById 方法:
/** * 根据id查询员工 * @param id * @return */ Employee getById(Long id);
3). Service层实现类
在 EmployeeServiceImpl 中实现 getById 方法:
/** * 根据id查询员工 * * @param id * @return */ public Employee getById(Long id) { Employee employee = employeeMapper.getById(id); employee.setPassword("****"); return employee; }
4). Mapper层
在 EmployeeMapper 接口中声明 getById 方法:
/** * 根据id查询员工信息 * @param id * @return */ @Select("select * from employee where id = #{id}") Employee getById(Long id);
修改员工信息功能
1). Controller层
在 EmployeeController 中创建 update 方法:
/** * 编辑员工信息 * @param employeeDTO * @return */ @PutMapping @ApiOperation("编辑员工信息") public Result update(@RequestBody EmployeeDTO employeeDTO){ log.info("编辑员工信息:{}", employeeDTO); employeeService.update(employeeDTO); return Result.success(); }
2). Service层接口
在 EmployeeService 接口中声明 update 方法:
/** * 编辑员工信息 * @param employeeDTO */ void update(EmployeeDTO employeeDTO);
3). Service层实现类
在 EmployeeServiceImpl 中实现 update 方法:
/** * 编辑员工信息 * * @param employeeDTO */ public void update(EmployeeDTO employeeDTO) { Employee employee = new Employee(); BeanUtils.copyProperties(employeeDTO, employee); employee.setUpdateTime(LocalDateTime.now()); employee.setUpdateUser(BaseContext.getCurrentId()); employeeMapper.update(employee); }
在实现启用禁用员工账号功能时,已实现employeeMapper.update(employee),在此不需写Mapper层代码。
2.4.3 功能测试
接口文档测试
分别测试根据id查询员工信息和编辑员工信息两个接口
1). 根据id查询员工信息
查询employee表中的数据,以id=6的记录为例
开始测试
获取到了id=4的相关员工信息
2). 编辑员工信息
修改id=6的员工信息,name由王五改为洁哥,username由wangwu改为jiege。
查看employee表数据
前后端联调测试
进入到员工列表查询,对员工姓名为张三的员工数据修改,点击修改,数据已回显
2.4.4 代码提交
commit—describe—push
2.5 导入分类模块功能代码
2.5.1 需求分析与设计
产品原型
后台系统中可以管理分类信息,分类包括两种类型,分别是 菜品分类 和 套餐分类 。
先来分析菜品分类相关功能。
**新增菜品分类:**当我们在后台系统中添加菜品时需要选择一个菜品分类,在移动端也会按照菜品分类来展示对应的菜品。
**菜品分类分页查询:**系统中的分类很多的时候,如果在一个页面中全部展示出来会显得比较乱,不便于查看,所以一般的系统中都会以分页的方式来展示列表数据。
**根据id删除菜品分类:**在分类管理列表页面,可以对某个分类进行删除操作。需要注意的是当分类关联了菜品或者套餐时,此分类不允许删除。
**修改菜品分类:**在分类管理列表页面点击修改按钮,弹出修改窗口,在修改窗口回显分类信息并进行修改,最后点击确定按钮完成修改操作。
**启用禁用菜品分类:**在分类管理列表页面,可以对某个分类进行启用或者禁用操作。
**分类类型查询:**当点击分类类型下拉框时,从数据库中查询所有的菜品分类数据进行展示。
分类管理原型:
业务规则:
- 分类名称必须是唯一的
- 分类按照类型可以分为菜品分类和套餐分类
- 新添加的分类状态默认为“禁用”
接口设计
根据上述原型图分析,菜品分类模块共涉及6个接口。
- 新增分类
- 分类分页查询
- 根据id删除分类
- 修改分类
- 启用禁用分类
- 根据类型查询分类
1). 新增分类
2). 分类分页查询
3). 根据id删除分类
4). 修改分类
5). 启用禁用分类
6). 根据类型查询分类
表设计
category表结构:
字段名 数据类型 说明 备注 id bigint 主键 自增 name varchar(32) 分类名称 唯一 type int 分类类型 1菜品分类 2套餐分类 sort int 排序字段 用于分类数据的排序 status int 状态 1启用 0禁用 create_time datetime 创建时间 update_time datetime 最后修改时间 create_user bigint 创建人id update_user bigint 最后修改人id
2.5.2 代码开发
Mapper层
DishMapper.java
package com.sky.mapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface DishMapper { /** * 根据分类id查询菜品数量 * @param categoryId * @return */ @Select("select count(id) from dish where category_id = #{categoryId}") Integer countByCategoryId(Long categoryId); }
SetmealMapper.java
package com.sky.mapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface SetmealMapper { /** * 根据分类id查询套餐的数量 * @param id * @return */ @Select("select count(id) from setmeal where category_id = #{categoryId}") Integer countByCategoryId(Long id); }
CategoryMapper.java
package com.sky.mapper; import com.github.pagehelper.Page; import com.sky.dto.CategoryPageQueryDTO; import com.sky.entity.Category; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface CategoryMapper { /** * 插入数据 * @param category */ @Insert("insert into category(type, name, sort, status, create_time, update_time, create_user, update_user)" + " VALUES" + " (#{type}, #{name}, #{sort}, #{status}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})") void insert(Category category); /** * 分页查询 * @param categoryPageQueryDTO * @return */ Page<Category> pageQuery(CategoryPageQueryDTO categoryPageQueryDTO); /** * 根据id删除分类 * @param id */ @Delete("delete from category where id = #{id}") void deleteById(Long id); /** * 根据id修改分类 * @param category */ void update(Category category); /** * 根据类型查询分类 * @param type * @return */ List<Category> list(Integer type); }
CategoryMapper.xml,进入到resources/mapper目录下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.sky.mapper.CategoryMapper"> <select id="pageQuery" resultType="com.sky.entity.Category"> select * from category <where> <if test="name != null and name != ''"> and name like concat('%',#{name},'%') </if> <if test="type != null"> and type = #{type} </if> </where> order by sort asc , create_time desc </select> <update id="update" parameterType="Category"> update category <set> <if test="type != null"> type = #{type}, </if> <if test="name != null"> name = #{name}, </if> <if test="sort != null"> sort = #{sort}, </if> <if test="status != null"> status = #{status}, </if> <if test="updateTime != null"> update_time = #{updateTime}, </if> <if test="updateUser != null"> update_user = #{updateUser} </if> </set> where id = #{id} </update> <select id="list" resultType="Category"> select * from category where status = 1 <if test="type != null"> and type = #{type} </if> order by sort asc,create_time desc </select> </mapper>
Service层
CategoryService.java
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 java.util.List; public interface CategoryService { /** * 新增分类 * @param categoryDTO */ void save(CategoryDTO categoryDTO); /** * 分页查询 * @param categoryPageQueryDTO * @return */ PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO); /** * 根据id删除分类 * @param id */ void deleteById(Long id); /** * 修改分类 * @param categoryDTO */ void update(CategoryDTO categoryDTO); /** * 启用、禁用分类 * @param status * @param id */ void startOrStop(Integer status, Long id); /** * 根据类型查询分类 * @param type * @return */ List<Category> list(Integer type); }
CategoryServiceImpl.java
package com.sky.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.sky.constant.MessageConstant; 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.exception.DeletionNotAllowedException; import com.sky.mapper.CategoryMapper; import com.sky.mapper.DishMapper; import com.sky.mapper.SetmealMapper; import com.sky.result.PageResult; import com.sky.service.CategoryService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; /** * 分类业务层 */ @Service @Slf4j public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryMapper categoryMapper; @Autowired private DishMapper dishMapper; @Autowired private SetmealMapper setmealMapper; /** * 新增分类 * @param categoryDTO */ public void save(CategoryDTO categoryDTO) { Category category = new Category(); //属性拷贝 BeanUtils.copyProperties(categoryDTO, category); //分类状态默认为禁用状态0 category.setStatus(StatusConstant.DISABLE); //设置创建时间、修改时间、创建人、修改人 category.setCreateTime(LocalDateTime.now()); category.setUpdateTime(LocalDateTime.now()); category.setCreateUser(BaseContext.getCurrentId()); category.setUpdateUser(BaseContext.getCurrentId()); categoryMapper.insert(category); } /** * 分页查询 * @param categoryPageQueryDTO * @return */ public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) { PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize()); //下一条sql进行分页,自动加入limit关键字分页 Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO); return new PageResult(page.getTotal(), page.getResult()); } /** * 根据id删除分类 * @param id */ public void deleteById(Long id) { //查询当前分类是否关联了菜品,如果关联了就抛出业务异常 Integer count = dishMapper.countByCategoryId(id); if(count > 0){ //当前分类下有菜品,不能删除 throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH); } //查询当前分类是否关联了套餐,如果关联了就抛出业务异常 count = setmealMapper.countByCategoryId(id); if(count > 0){ //当前分类下有菜品,不能删除 throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL); } //删除分类数据 categoryMapper.deleteById(id); } /** * 修改分类 * @param categoryDTO */ public void update(CategoryDTO categoryDTO) { Category category = new Category(); BeanUtils.copyProperties(categoryDTO,category); //设置修改时间、修改人 category.setUpdateTime(LocalDateTime.now()); category.setUpdateUser(BaseContext.getCurrentId()); categoryMapper.update(category); } /** * 启用、禁用分类 * @param status * @param id */ public void startOrStop(Integer status, Long id) { Category category = Category.builder() .id(id) .status(status) .updateTime(LocalDateTime.now()) .updateUser(BaseContext.getCurrentId()) .build(); categoryMapper.update(category); } /** * 根据类型查询分类 * @param type * @return */ public List<Category> list(Integer type) { return categoryMapper.list(type); } }
Controller层
CategoryController.java
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") @Api(tags = "分类相关接口") @Slf4j public class CategoryController { @Autowired private CategoryService categoryService; /** * 新增分类 * @param categoryDTO * @return */ @PostMapping @ApiOperation("新增分类") public Result<String> save(@RequestBody CategoryDTO categoryDTO){ log.info("新增分类:{}", categoryDTO); categoryService.save(categoryDTO); return Result.success(); } /** * 分类分页查询 * @param categoryPageQueryDTO * @return */ @GetMapping("/page") @ApiOperation("分类分页查询") public Result<PageResult> page(CategoryPageQueryDTO categoryPageQueryDTO){ log.info("分页查询:{}", categoryPageQueryDTO); PageResult pageResult = categoryService.pageQuery(categoryPageQueryDTO); return Result.success(pageResult); } /** * 删除分类 * @param id * @return */ @DeleteMapping @ApiOperation("删除分类") public Result<String> deleteById(Long id){ log.info("删除分类:{}", id); categoryService.deleteById(id); return Result.success(); } /** * 修改分类 * @param categoryDTO * @return */ @PutMapping @ApiOperation("修改分类") public Result<String> update(@RequestBody CategoryDTO categoryDTO){ categoryService.update(categoryDTO); return Result.success(); } /** * 启用、禁用分类 * @param status * @param id * @return */ @PostMapping("/status/{status}") @ApiOperation("启用禁用分类") public Result<String> startOrStop(@PathVariable("status") Integer status, Long id){ categoryService.startOrStop(status,id); return Result.success(); } /** * 根据类型查询分类 * @param type * @return */ @GetMapping("/list") @ApiOperation("根据类型查询分类") public Result<List<Category>> list(Integer type){ List<Category> list = categoryService.list(type); return Result.success(list); } }
2.5.3 功能测试
接口测试、前后端联调……
2.5.4 代码提交
commit—describe—push