- 一、软件开发整体介绍
- 1、软件开发流程
- 2、角色分工
- 3、软件环境
- 二、瑞吉外卖项目介绍
- 1、项目介绍
- 2、产品原型展示
- 3、技术选型
- 4、功能架构
- 5、角色
- 三、环境搭建
- 1、数据库搭建
- 1.1、创建数据库
- 1.2、执行SQL脚本
- 1.3、数据表
- 2、maven项目搭建
- 2.1、创建
- 2.2、解决IDEA加载maven工程缓慢
- 2.3、添加依赖
- 2.4、application.yml
- 2.5、配置application启动类
- 2.6、把前端的静态资源放在resource目录
- 2.7、设置静态资源映射
- 2.8、启动项目
- 四、后台登录功能开发
- 1、需求分析
- 1.1、登录页面展示
- 1.2、查看登录请求信息
- 1.3、数据模型(employee表)
- 2、代码开发
- 2.1、创建实体类Employee,和employee表进行映射
- 2.2、创建Mapper、Service、Controller
- 五、后台退出功能开发
- 1、需求分析
- 2、代码实现
- 六、完善登录功能
- 1、问题分析
- 2、代码实现
- 2.1、创建自定义过滤器LoginCheckFilter
- 2.2、在启动类上加入注解@ServletComponentScan
- 2.3、完善过滤器的处理逻辑
- 七、新增员工
- 1、需求分析
- 2、数据模型
- 3、代码开发
- 八、员工信息分页查询
- 1、需求分析
- 2、代码开发
- 2.1、配置MP分页插件
- 2.2、员工信息分页查询
- 2.3、功能测试
- 九、启用/禁用员工账号
- 1、需求分析
- 2、代码开发
- 2.1、根据id修改员工信息
- 3、代码修复
- 十、编辑员工信息
- 1、需求分析
- 2、代码开发
- 十一、分类管理业务开发
- 1、公共字段自动填充
- 1.1、问题分析
- 1.2、代码实现
- 2.4、功能完善
- 2、新增分类
- 2.1、需求分析
- 2.2、数据模型
- 2.3、代码开发
- 十二、分类信息分页查询
- 1、需求分析
- 2、代码开发
- 3、删除分类
- 3.1、需求分析
- 3.2、代码开发
- 3.3、代码完善
- 3.4、关键代码
- 4、修改分类
- 4.1、需求分析
- 4.2、代码实现
配置VM Options参数,打开路径:File ----> Setting ----> Build, Exclusion, Deployment ----> Build Tools ----> Maven ----> Runner 页面下的VM Option设置如下参数:
-DarchetypeCatalog=internal2.3、添加依赖
2.4、application.yml4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.5 com.itheima reggie_take_out 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web compile com.baomidou mybatis-plus-boot-starter 3.4.2 org.projectlombok lombok 1.18.20 com.alibaba fastjson 1.2.76 commons-lang commons-lang 2.6 mysql mysql-connector-java runtime com.alibaba druid-spring-boot-starter 1.1.23 org.springframework.boot spring-boot-maven-plugin 2.4.5
server:
port: 8080
spring:
application:
#应用的名称,可选
name: reggie_take_out
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
2.5、配置application启动类
package com.itheima.reggie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Slf4j
@SpringBootApplication
public class ReggieApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieApplication.class,args);
log.info("项目启动成功...");
}
}
2.6、把前端的静态资源放在resource目录
2.7、设置静态资源映射
package com.itheima.reggie.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始静态资源映射");
registry.addResourceHandler("/backend
@Data
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String sex;
private String idNumber;//身份证号码
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}
2.2、创建Mapper、Service、Controller
- EmployeeMapper
package com.itheima.reggie.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.itheima.reggie.entity.Employee; import org.apache.ibatis.annotations.Mapper; @Mapper public interface EmployeeMapper extends BaseMapper{ }
- EmployeeService
package com.itheima.reggie.service; import com.baomidou.mybatisplus.extension.service.IService; import com.itheima.reggie.entity.Employee; public interface EmployeeService extends IService{ }
- EmployeeServiceImpl
package com.itheima.reggie.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.itheima.reggie.entity.Employee; import com.itheima.reggie.mapper.EmployeeMapper; import com.itheima.reggie.service.EmployeeService; import org.springframework.stereotype.Service; @Service public class EmployeeServiceImpl extends ServiceImplimplements EmployeeService{ }
- EmployeeController
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeServiceImpl employeeService;
}
- 导入返回结果类R
- 此类是一个通用结果类,服务端响应的所有结果最终都会包装成此种类型返回给前端页面
package com.itheima.reggie.common; import lombok.Data; import java.util.HashMap; import java.util.Map; @Data public class R{ private Integer code; //编码:1成功,0和其它数字为失败 private String msg; //错误信息 private T data; //数据 private Map map = new HashMap(); //动态数据 public static R success(T object) { R r = new R (); r.data = object; r.code = 1; return r; } public static R error(String msg) { R r = new R(); r.msg = msg; r.code = 0; return r; } public R add(String key, Object value) { this.map.put(key, value); return this; } }
- 在Controller中创建登录方法
package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/login")
public R login(HttpServletRequest request,@RequestBody Employee employee){
//1、将页面提交的密码password进行md5加密处理
String password = employee.getPassword();
password = DigestUtils.md5DigestAsHex(password.getBytes());
//2、根据页面提交的用户名username查询数据库
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Employee::getUsername,employee.getUsername());
Employee emp = employeeService.getOne(queryWrapper);
//3、如果没有查询到则返回登录失败结果
if(emp == null){
return R.error("登录失败");
}
//4、密码比对,如果不一致则返回登录失败结果
if(!emp.getPassword().equals(password)){
return R.error("登录失败");
}
//5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
if(emp.getStatus() == 0){
return R.error("账号已禁用");
}
//6、登录成功,将员工id存入Session并返回登录成功结果
request.getSession().setAttribute("employee",emp.getId());
return R.success(emp);
}
@PostMapping("/logout")
public R logout(HttpServletRequest request){
//清理Session中保存的当前登录员工的id
request.getSession().removeAttribute("employee");
return R.success("退出成功");
}
}
五、后台退出功能开发
1、需求分析
2、代码实现
在Controller中创建退出方法
//员工退出
@PostMapping("/logout")
public R logout(HttpServletRequest request){
//清理Session中保存的当前员工登录的id
request.getSession().removeAttribute("employee");
return R.success("退出成功");
}
六、完善登录功能
1、问题分析
前面我们已经完成了后台系统的员工登录功能开发,但是还存在一个问题:用户如果不登录,直接访问系统首页面,照样可以正常访问。
这种设计并不合理,我们希望看到的效果应该是,只有登录成功后才可以访问系统中的页面,如果没有登录则跳转到登录页面。
那么,具体应该怎么实现呢?
答案就是使用过滤器或者拦截器,在过滤器或者拦截器中判断用户是否已经完成登录,如果没有登录则跳转到登录页面
2、代码实现实现步骤:
2.1、创建自定义过滤器LoginCheckFilter@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "
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_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(BigInteger.class, ToStringSerializer.instance)
.addSerializer(Long.class, ToStringSerializer.instance)
.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) 在WebMvcConfig配置类中扩展Spring mvc的消息转换器,在此消息转换器中使用提供的对象转换器进行Java对象到json数据的转换
@Override protected void extendMessageConverters(List十、编辑员工信息 1、需求分析> converters) { //创建消息转换器 MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); //设置对象转换器,底层使用Jackson将Java转换为json messageConverter.setObjectMapper(new JacksonObjectMapper()); //将上面的消息转换器对象追加到mvc框架的转换器集合中 converters.add(0,messageConverter); super.extendMessageConverters(converters); }
在员工管理列表页面点击编辑按钮,跳转到编辑页面,在编辑页面回显员工信息并进行修改,最后点击保存按钮完成编辑操作
2、代码开发在开发代码之前需要梳理一下操作过程和对应的程序的执行流程:
1、点击编辑按钮时,页面跳转到add.html,并在url中携带参数[员工id]
2、在add.html页面获取url中的参数[员工id]
3、发送ajax请求,请求服务端,同时提交员工id参数
4、服务端接收请求,根据员工id查询员工信息,将员工信息以json形式响应给页面
//根据id查询员工信息
@GetMapping("/{id}")
public R getById(@PathVariable String id){
log.info("根据id查对象");
Employee emp = employeeService.getById(id);
if(emp!=null){
return R.success(emp);
}
return R.error("没有查询到该用户信息");
}
5、页面接收服务端响应的json数据,通过VUE的数据绑定进行员工信息回显
6、点击保存按钮,发送ajax请求,将页面中的员工信息以json方式提交给服务端
7、服务端接收员工信息,并进行处理,完成后给页面响应
8、页面接收到服务端响应信息后进行相应处理
注意:add.html页面为公共页面,新增员工和编辑员工都是在此页面操作,所以该代码部分与之前添加员工代码对应,不需要重写。
十一、分类管理业务开发 1、公共字段自动填充 1.1、问题分析前面我们已经完成了后台系统的员工管理功能开发,在新增员工时需要设置创建时间、创建人、修改时间、修改人等字段,在编辑员工时需要设置修改时间和修改人等字段。这些字段属于公共字段,也就是很多表中都有这些字段,如下:
能不能对于这些公共字段在某个地方统一处理,来简化开发呢?答案就是使用Mybatis Plus提供的公共字段自动填充功能。
1.2、代码实现Mybatis Plus公共字段自动填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。
实现步骤:
1、在实体类的属性上加入@TableField注解,指定自动填充的策略
@TableField(fill = FieldFill.INSERT)//插入时填充字段 private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新时填充字段 private LocalDateTime updateTime; @TableField(fill = FieldFill.INSERT) private Long createUser; @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateUser;
2、按照框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectHandler接口
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时自动填充
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充【insert】。。。");
log.info(metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser",new Long(1));
metaObject.setValue("updateUser",new Long(1));
}
//更新时自动填充
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充【update】。。。");
log.info(metaObject.toString());
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("updateUser",new Long(1));
}
}
2.4、功能完善
前面我们已经完成了公共字段自动填充功能的代码开发,但是还有一个问题没有解决,就是我们在自动填充createUser和updateUser时设置的用户id是固定值,现在我们需要改造成动态获取当前登录用户的id。
有的同学可能想到,用户登录成功后我们将用户id存入了HttpSession中,现在我从HttpSession中获取不就行了?
注意,我们在MyMetaObjectHandler类中是不能获得HttpSession对象的,所以我们需要通过其他方式来获取登录用户id。
可以使用ThreadLocal来解决此问题,它是JDK中提供的一个类。
在学习ThreadLocal之前,我们需要先确认一个事情,就是客户端发送的每次http请求,对应的在服务端都会分配一个新的线程来处理,在处理过程中涉及到下面类中的方法都属于相同的一个线程:
1、LoginCheckFilter的doFilter方法
2、EmployeeContraller的update方法
3、MyMetaObjectHandler的updateFill方法
可以在上面的三个方法中分别加入下面代码(获取当前线程id):
long id = Thread.currentThread().getId() ;
log.info("线程id:{}" ,id);
执行编辑员工功能进行验证,通过观察控制台输出可以发现,一次请求对应的线程id是相同的:
什么是ThreadLocal?
ThreadLocal并不是一个Thread,而是Thread的局部变量。当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。
ThreadLocal常用方法:
- public void set(T value) 设置当前线程局部变量的值
- public T get() 返回当前线程所对应的线程局部变量的值
我们可以在LoginCheckFilter的doFilter方法中获取当前登录用户id,并调用ThreadLocal的set方法来设置当前线程的线程局部变量的值(用户id),然后在MyMetaObjectHandler的updateFill方法中调用ThreadLocal的get方法来获得当前线程所对应的线程局部变量的值(用户id)。
实现步骤:
1、编写BaseContext工具类,基于ThreadLocal封装的工具类
public class BaseContext {
private static ThreadLocal threadLocal=new ThreadLocal<>();
public static void setCurrentId(Long id){
threadLocal.set(id);
}
public static Long getCurrentId(){
return threadLocal.get();
}
}
2、在LogincheckFilter的doFilter方法中调用BaseContext来设置当前登录用户的id
if (request.getSession().getAttribute("employee") != null) {
log.info("用户已登录,用户id为:{}", request.getSession().getAttribute("employee"));
Long empId= (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
filterChain.doFilter(request, response);
return;
}
3、在MyMeta0bjectHandler的方法中调用BaseContext获取登录用户的id
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时自动填充
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充【insert】。。。");
log.info(metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser",BaseContext.getCurrentId());
metaObject.setValue("updateUser",BaseContext.getCurrentId());
}
//更新时自动填充
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充【update】。。。");
log.info(metaObject.toString());
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("updateUser",BaseContext.getCurrentId());
}
}
2、新增分类
2.1、需求分析
后台系统中可以管理分类信息,分类包括两种类型,分别是菜品分类和套餐分类。当我们在后台系统中添加菜品时需要选择一个菜品分类,当我们在后台系统中添加一个套餐时需要选择一个套餐分类,在移动端也会按照菜品分类和套餐分类来展示对应的菜品和套餐。
新增分类,其实就是将我们新增窗口录入的分类数据插入到category表,表结构如下:
2.3、代码开发在开发业务功能前,先将需要用到的类和接口基本结构创建好:
- 实体类Category(直接从课程资料中导入即可)
@Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//类型 1 菜品分类 2 套餐分类
private Integer type;
//分类名称
private String name;
//顺序
private Integer sort;
//创建时间
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
//创建人
@TableField(fill = FieldFill.INSERT)
private Long createUser;
//修改人
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}
- Mapper接口CategoryMapper
@Mapper public interface CategoryMapper extends BaseMapper{ }
- 业务层接口CategoryService
public interface CategoryService extends IService{ }
- 业务层实现类CategoryServicelmpl
@Service public class CategoryServicelmpl extends ServiceImplimplements CategoryService { }
- 控制层CategoryController
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
}
在开发代码之前,需要梳理一下整个程序的执行过程:
1、页面(backend/page/category/list.html)发送ajax请求,将新增分类窗口输入的数据以json形式提交到服务端
2、服务端Controller接收页面提交的数据并调用Service将数据进行保存
3、Service调用Mapper操作数据库,保存数据
可以看到新增菜品分类和新增套餐分类请求的服务端地址和提交的json数据结构相同,所以服务端只需要提供一个方法统一处理即可
//新增分类 @PostMapping public R十二、分类信息分页查询 1、需求分析save(@RequestBody Category category){ log.info("category:{}",category); categoryService.save(category); return R.success("新增分类成功"); }
系统中的分类很多的时候,如果在一个页面中全部展示出来会显得比较乱,不便于查看,所以一般的系统中都会以分页的方式来展示列表数据。
2、代码开发在开发代码之前,需要梳理一下整个程序的执行过程:
1、页面发送ajax请求,将分页查询参数(page.pageSize)提交到服务端
2、服务端Controller接收页面提交的数据并调用Service查询数据
3、Service调用Mapper操作数据库,查询分页数据
4、Controller将查询到的分页数据响应给页面
5、页面接收到分页数据并通过ElementUI的Table组件展示到页面上
@GetMapping("/page")
public R page(int page, int pageSize) {
//构造分页构造器
Page pageInfo=new Page<>(page,pageSize);
//构造条件构造器
LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper<>();
//添加排序条件,根据sort进行排序
queryWrapper.orderByAsc(Category::getSort);
//进行分页查询
categoryService.page(pageInfo,queryWrapper);
return R.success(pageInfo);
}
注意:要把Category中的private Integer isDeleted;注释掉才能查询到数据
3、删除分类 3.1、需求分析在分类管理列表页面,可以对某个分类进行删除操作。需要注意的是当分类关联了菜品或者套餐时,此分类不允许删除。
3.2、代码开发在开发代码之前,需要梳理一下整个程序的执行过程:
1、页面发送ajax请求,将参数(id)提交到服务端
2、服务端Controller接收页面提交的数据并调用Service删除数据
3、Service调用Mapper操作数据库
//根据id删除分类 @DeleteMapping public R3.3、代码完善delete(Long ids){ log.info("删除分类,id为{}",ids); categoryService.removeById(ids); //代码完善之后categoryService.remove(ids); return R.success("分类信息删除成功"); }
前面我们已经实现了根据id删除分类的功能,但是并没有检查删除的分类是否关联了菜品或者套餐,所以我们需要进行功能完善。
要完善分类删除功能,需要先准备基础的类和接口:
1、实体类Dish和Setmeal (从课程资料中复制即可)
@Data
public class Dish implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//菜品名称
private String name;
//菜品分类id
private Long categoryId;
//菜品价格
private BigDecimal price;
//商品码
private String code;
//图片
private String image;
//描述信息
private String description;
//0 停售 1 起售
private Integer status;
//顺序
private Integer sort;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}
@Data
public class Setmeal implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//分类id
private Long categoryId;
//套餐名称
private String name;
//套餐价格
private BigDecimal price;
//状态 0:停用 1:启用
private Integer status;
//编码
private String code;
//描述信息
private String description;
//图片
private String image;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}
2、Mapper接口DishMapper和SetmealMapper
@Mapper public interface DishMapper extends BaseMapper{ } @Mapper public interface SetmealMapper extends BaseMapper { }
3、Service接口DishService和SetmealService
public interface DishService extends IService{ } public interface SetmealService extends IService { }
4、Service实现类DishServicelmpl和SetmealServicelmpl
@Service public class DishServiceImpl extends ServiceImpl3.4、关键代码implements DishService { } @Service public class SetmealServiceImpl extends ServiceImpl implements SetmealService{ }
- 在CategoryService添加remove方法
public interface CategoryService extends IService{ public void remove(Long id); }
- 在CategoryServicelmpl实现remove方法
@Service public class CategoryServicelmpl extends ServiceImplimplements CategoryService { @Autowired private DishService dishService; @Autowired private SetmealService setmealService; @Override public void remove(Long id) { LambdaQueryWrapper dishLambdaQueryWrapper=new LambdaQueryWrapper<>(); //添加查询条件,根据分类id进行查询 dishLambdaQueryWrapper.eq(Dish::getCategoryId,id); int count1 = dishService.count(dishLambdaQueryWrapper); //查询当前分类是否关联菜品,如果已经关联,抛出业务异常 if(count1>0){ //已经关联菜品,抛出业务异常 throw new CustomException("已经关联菜品,不能删除"); } //查询当前分类是否关联了套餐,如果已经关联,抛出业务异常 LambdaQueryWrapper setmealLambdaQueryWrapper=new LambdaQueryWrapper<>(); //添加查询条件,根据分类id进行查询 setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id); int count2 = setmealService.count(setmealLambdaQueryWrapper); if(count2>0){ //已经关联套餐,抛出业务异常 throw new CustomException("已经关联套餐,不能删除"); } //正常删除分类 super.removeById(id); } }
- 定义异常类CustomException
public class CustomException extends RuntimeException{
public CustomException(String message){
super(message);
}
}
- 在全局异常处理器GlobalExceptionHandler添加
//进行异常处理方法 @ExceptionHandler(CustomException.class) public R4、修改分类 4.1、需求分析exceptionHandler(CustomException ex){ log.error(ex.getMessage()); return R.error(ex.getMessage()); }
在分类管理列表页面点击修改按钮,弹出修改窗口,在修改窗口回显分类信息并进行修改,最后点击确定按钮完成修改操作
4.2、代码实现//修改分类 @PutMapping public Rupdate(@RequestBody Category category){ categoryService.updateById(category); return R.success("分类修改成功");



