目录
一、公共字段自动填充
1.1 问题分析
1.2 代码实现
编辑 1.2.1 修改实体类Employee
1.2.2 MyMetaObjectHandler
1.2.3 EmployeeController将新增、修改方法当中的公共字段赋值注释掉
1.3 功能测试
1.4 功能完善
1.4.1 BaseContext
1.4.2 LoginCheckFilter优化将用户id塞进线程
1.4.3 MyMetaObjectHandler
二、新增分类
2.1 需求分析
2.2 数据模型
2.3 代码实现
2.3.1 实体类Category
2.3.2 CategoryMapper
2.3.3 CategoryService
2.3.4 CategoryServiceImpl
2.3.5 CategoryController
2.3.6 CategoryController新增save方法
2.4 功能测试
三、分类信息分页查询
3.1 需求分析
3.2 代码实现
3.2.1 CategoryController
3.2.1 Category注释是否删除字段
3.3 功能测试
四、删除分类
4.1 需求分析
4.2 代码实现
4.2.1 CategoryController
4.3 功能测试
4.4 功能完善
4.4.1 菜品实体类Dish
4.4.2 套餐实体类Setmeal
4.4.3 DishMapper
4.4.4 SetmealMapper
4.4.5 DishService
4.4.6 SetmealService
4.4.7 DishServiceImpl
4.4.8 SetmealServiceImpl
4.4.9 修改CategoryService
4.4.10 自定义业务异常类CustomException
4.4.11 CategoryServiceImpl
4.4.12 GlobaExceptionHandler
4.4.13 CategoryController
五、修改分类
5.1 需求分析
5.2 代码实现
5.2.1 CategoryController
5.3 功能测试
前言:公共字段自动填充实现,删除业务逻辑实现
package com.runa.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@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;
@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;
}
package com.runa.reggie.common;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
* @param metaObject
*/
@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());
}
/**
* 更新操作,自动填充
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充[update]...");
log.info(metaObject.toString());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
}
package com.runa.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Employee;
import com.runa.reggie.service.impl.EmployeeServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeServcie employeeServcie;
/**
* 员工登录
* @param request
* @param employee
* @return
*/
//HttpServletRequest request 是为了将登录对象塞入session
@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 = employeeServcie.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("emplyee");
return R.success("退出成功!");
}
@PostMapping
public R save(HttpServletRequest request, @RequestBody Employee employee){
log.info("新增员工,员工信息为:{}",employee.toString());
// 设置初始密码123456,需要进行md5加密处理
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
// employee.setCreateTime(LocalDateTime.now());
// employee.setUpdateTime(LocalDateTime.now());
// //获得当前用户的id
// Long empId = (Long) request.getSession().getAttribute("employee");
// employee.setCreateUser(empId);
// employee.setUpdateUser(empId);
employeeServcie.save(employee);
return R.success("新增员工成功");
}
/**
* 员工信息分页查询
* @param page
* @param pageSize
* @param name
* @return
*/
@GetMapping("/page")
public R page(int page, int pageSize,String name){
log.info("page= {}, pageSize= {}, name = {}",page, pageSize, name);
// 构造分页构造器
Page pageInfo = new Page(page, pageSize);
//构造条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper();
// 添加过滤条件//当传入的name不为空的时候才会添加条件
queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
// 添加排序条件
queryWrapper.orderByDesc(Employee::getUpdateTime);
//执行查询
employeeServcie.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
/**
* 根据ID修改员工信息
* @param employee
* @return
*/
@PutMapping
public R update(HttpServletRequest request, @RequestBody Employee employee){
log.info(employee.toString());
// Long empId = (Long) request.getSession().getAttribute("employee");
// employee.setUpdateUser(empId);
// employee.setUpdateTime(LocalDateTime.now());
employeeServcie.updateById(employee);
return R.success("员工信息修改成功");
}
@GetMapping("/{id}")
public R GetById(@PathVariable Long id){
log.info("根据id查询员工:{}",id);
Employee employee = employeeServcie.getById(id);
if(employee != null){
return R.success(employee);
}
return R.error("没有查询到对应员工信息");
}
}
package com.runa.reggie.common;
public class BaseContext {
private static ThreadLocal threadLocal = new ThreadLocal<>();
/**
* 设置值
* @param id
*/
public static void setCurrentId(Long id){
threadLocal.set(id);
}
/**
* 获取值
* @return
*/
public static Long getCurrentId(){
return threadLocal.get();
}
}
package com.runa.reggie.filter;
import com.alibaba.fastjson.JSON;
import com.runa.reggie.common.BaseContext;
import com.runa.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
// 路径匹配器
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 1 获取本次请求的URI
// request.getRequestURL()返回的是全路径。
// request.getRequestURI()返回的是除去协议,域名(IP+端口号)之后的路由部分。
String requestURI = request.getRequestURI();
log.info("拦截到请求:【{}】",requestURI);
// 定义一些不需要处理的路径
String[] urls = new String[]{
"/employee/login", // 登录不需要
"/employee/logout",
"/backend/**",
"/front/**"
};
// 2 判断本次请求是否需要处理
boolean check = check(urls, requestURI);
// 3 如果不需要处理,则直接放行
if(check){
log.info("本次请求【 {} 】 不需要处理",requestURI);
filterChain.doFilter(request,response);
return;
}
// 4 判断登录状态,如果已登录,则直接放行
if(request.getSession().getAttribute("employee") != null){
log.info("用户已登录,请求url为:【{}】, 用户id为:【 {} 】 ",requestURI,request.getSession().getAttribute("employee"));
// 获取ID 塞进线程
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
filterChain.doFilter(request,response);
return;
}
log.info("用户未登录");
// 5 如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/**
* 路径匹配,检查本次请求是否需要放行
* @param urls
* @param requestURI
* @return
*/
public boolean check(String[] urls, String requestURI){
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if(match){
return true;
}
}
// 循环都匹配不上就返回false
return false;
}
}
package com.runa.reggie.common;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
* @param metaObject
*/
@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.getCurrent());
metaObject.setValue("updateUser", BaseContext.getCurrent());
}
/**
* 更新操作,自动填充
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充[update]...");
log.info(metaObject.toString());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrent());
}
}
package com.runa.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 分类
*/
@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;
}
package com.runa.reggie.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.runa.reggie.entity.Category;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CategoryMapper extends BaseMapper {
}
package com.runa.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Category;
public interface CategoryService extends IService {
}
package com.runa.reggie.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runa.reggie.entity.Category;
import com.runa.reggie.mapper.CategoryMapper;
import com.runa.reggie.service.CategoryService;
import org.springframework.stereotype.Service;
@Service
public class CategoryServiceImpl extends ServiceImpl implements CategoryService {
}
package com.runa.reggie.controller;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
}
package com.runa.reggie.controller;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Category;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R save(@RequestBody Category category){
log.info("新增分类:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
}
package com.runa.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Category;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R save(@RequestBody Category category){
log.info("新增分类:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
/**
* 分页查询
* @param page
* @param pageSize
* @return
*/
@GetMapping("/page")
public R page(int page, int pageSize){
log.info("page= {}, pageSize= {}, name = {}",page, pageSize);
//分页构造器
Page pageInfo = new Page(page, pageSize);
// 条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
//添加排序条件,根据sort排序
queryWrapper.orderByAsc(Category::getSort);
//进行分页查询
categoryService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
}
package com.runa.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 分类
*/
@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;
}
注意传参是ids
package com.runa.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Category;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R save(@RequestBody Category category){
log.info("新增分类:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
/**
* 分页查询
* @param page
* @param pageSize
* @return
*/
@GetMapping("/page")
public R page(int page, int pageSize){
log.info("page= {}, pageSize= {}, name = {}",page, pageSize);
//分页构造器
Page pageInfo = new Page(page, pageSize);
// 条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
//添加排序条件,根据sort排序
queryWrapper.orderByAsc(Category::getSort);
//进行分页查询
categoryService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
/**
* 根据id删除分类
* @param ids
* @return
*/
@DeleteMapping
public R delete(Long ids){
log.info("根据ID删除分类:{}",ids);
categoryService.removeById(ids);
return R.success("分类信息删除成功");
}
}
package com.runa.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
菜品
*/
@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;
}
package com.runa.reggie.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 套餐
*/
@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;
}
package com.runa.reggie.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.runa.reggie.entity.Dish;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DishMapper extends BaseMapper {
}
package com.runa.reggie.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.runa.reggie.entity.Setmeal;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SetmealMapper extends BaseMapper {
}
package com.runa.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Dish;
public interface DishService extends IService {
}
package com.runa.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Setmeal;
public interface SetmealService extends IService {
}
package com.runa.reggie.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runa.reggie.entity.Dish;
import com.runa.reggie.mapper.DishMapper;
import com.runa.reggie.service.DishService;
import org.springframework.stereotype.Service;
@Service
public class DishServiceImpl extends ServiceImpl implements DishService {
}
package com.runa.reggie.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runa.reggie.entity.Setmeal;
import com.runa.reggie.mapper.SetmealMapper;
import com.runa.reggie.service.SetmealService;
import org.springframework.stereotype.Service;
@Service
public class SetmealServiceImpl extends ServiceImpl implements SetmealService {
}
package com.runa.reggie.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Category;
public interface CategoryService extends IService {
public void remove(Long ids);
}
package com.runa.reggie.common;
/**
* 自定义业务异常类
*/
public class CustomException extends RuntimeException {
public CustomException(String message){
super(message);
}
}
package com.runa.reggie.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runa.reggie.common.CustomException;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Dish;
import com.runa.reggie.entity.Setmeal;
import com.runa.reggie.mapper.CategoryMapper;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.DishService;
import com.runa.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CategoryServiceImpl extends ServiceImpl implements CategoryService {
@Autowired
private DishService dishService;
@Autowired
private SetmealService setmealService;
@Override
public void remove(Long ids) {
LambdaQueryWrapper dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//添加查询条件,根据分类id查询
dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
int count1 = dishService.count(dishLambdaQueryWrapper);
// 查询分类是否关联了菜品,如果关联了,抛出一个业务异常
if(count1 > 0){
// 关联了 抛出异常
throw new CustomException("当前分类下关联了菜品,不能删除");
}
LambdaQueryWrapper setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
//添加查询条件,根据分类id查询
setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);
int count2 = setmealService.count(setmealLambdaQueryWrapper);
// 查询分类是否关联了套餐,如果关联了,抛出一个业务异常
if(count2 > 0){
// 关联了 抛出异常
throw new CustomException("当前分类下关联了套餐,不能删除");
}
//执行删除
super.removeById(ids);
}
}
package com.runa.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* 全局异常处理
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class}) // 加了RestController Controller 注解的
@ResponseBody
@Slf4j
public class GlobaExceptionHandler {
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
String msg = ex.getMessage();
log.error(msg);
if(msg.contains("Duplicate entry")){
String[] split = msg.split(" "); //空分割
String resultMsg = split[2] + " 已存在 ";
return R.error(resultMsg);
}
return R.error("未知错误!");
}
/**
* 异常处理方法(处理自定义的)
* @return
*/
@ExceptionHandler(CustomException.class)
public R exceptionHandler(CustomException ex){
String msg = ex.getMessage();
log.error(msg);
return R.error(msg);
}
}
package com.runa.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Category;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R save(@RequestBody Category category){
log.info("新增分类:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
/**
* 分页查询
* @param page
* @param pageSize
* @return
*/
@GetMapping("/page")
public R page(int page, int pageSize){
log.info("page= {}, pageSize= {}, name = {}",page, pageSize);
//分页构造器
Page pageInfo = new Page(page, pageSize);
// 条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
//添加排序条件,根据sort排序
queryWrapper.orderByAsc(Category::getSort);
//进行分页查询
categoryService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
/**
* 根据id删除分类
* @param ids
* @return
*/
@DeleteMapping
public R delete(Long ids){
log.info("根据ID删除分类:{}",ids);
// categoryService.removeById(ids);
categoryService.remove(ids);
return R.success("分类信息删除成功");
}
}
package com.runa.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.Category;
import com.runa.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R save(@RequestBody Category category){
log.info("新增分类:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
/**
* 分页查询
* @param page
* @param pageSize
* @return
*/
@GetMapping("/page")
public R page(int page, int pageSize){
log.info("page= {}, pageSize= {}, name = {}",page, pageSize);
//分页构造器
Page pageInfo = new Page(page, pageSize);
// 条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
//添加排序条件,根据sort排序
queryWrapper.orderByAsc(Category::getSort);
//进行分页查询
categoryService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
/**
* 根据id删除分类
* @param ids
* @return
*/
@DeleteMapping
public R delete(Long ids){
log.info("根据ID删除分类:{}",ids);
// categoryService.removeById(ids);
categoryService.remove(ids);
return R.success("分类信息删除成功");
}
@PutMapping
public R update(@RequestBody Category category){
log.info("根据id更新分类信息:{}",category);
categoryService.updateById(category);
return R.success("修改分类信息成功");
}
}