当前位置: 首页 > news >正文

【java】【项目实战】[外卖四]分类管理业务开发

前言:公共字段自动填充实现,删除业务逻辑实现

一、公共字段自动填充

1.1 问题分析

1.2 代码实现

 1.2.1 修改实体类Employee

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;}

 1.2.2 MyMetaObjectHandler

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*/@Overridepublic 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));}/*** 更新操作,自动填充* @param metaObject*/@Overridepublic void updateFill(MetaObject metaObject) {log.info("公共字段自动填充[update]...");log.info(metaObject.toString());metaObject.setValue("updateTime", LocalDateTime.now());metaObject.setValue("updateUser", new Long(1));}
}

 1.2.3 EmployeeController将新增、修改方法当中的公共字段赋值注释掉 

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 {@Autowiredprivate EmployeeServcie employeeServcie;/*** 员工登录* @param request* @param employee* @return*///HttpServletRequest request  是为了将登录对象塞入session@PostMapping("/login")public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){//1、将页面提交的密码password进行md5加密处理String password = employee.getPassword();password = DigestUtils.md5DigestAsHex(password.getBytes());//2、根据页面提交的用户名username查询数据库LambdaQueryWrapper<Employee> 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<String> logout(HttpServletRequest request){// 清理Session 中保存的当前员工的idrequest.getSession().removeAttribute("emplyee");return R.success("退出成功!");}@PostMappingpublic R<String> 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> page(int page, int pageSize,String name){log.info("page= {}, pageSize= {}, name = {}",page, pageSize, name);// 构造分页构造器Page pageInfo = new Page(page, pageSize);//构造条件构造器LambdaQueryWrapper<Employee> 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*/@PutMappingpublic R<String> 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<Employee> GetById(@PathVariable Long id){log.info("根据id查询员工:{}",id);Employee employee = employeeServcie.getById(id);if(employee != null){return R.success(employee);}return R.error("没有查询到对应员工信息");}}

1.3 功能测试

1.4 功能完善

 

 

 1.4.1 BaseContext 

package com.runa.reggie.common;public class BaseContext {private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();public static void setCurrentId(Long id){threadLocal.set(id);}public static Long getCurrent(){return threadLocal.get();}
}

1.4.2 LoginCheckFilter优化将用户id塞进线程

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();@Overridepublic 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;}}// 循环都匹配不上就返回falsereturn false;}
}

1.4.3 MyMetaObjectHandler 

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*/@Overridepublic 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*/@Overridepublic void updateFill(MetaObject metaObject) {log.info("公共字段自动填充[update]...");log.info(metaObject.toString());metaObject.setValue("updateTime", LocalDateTime.now());metaObject.setValue("updateUser",  BaseContext.getCurrent());}
}

二、新增分类

2.1 需求分析

2.2 数据模型

2.3 代码实现

 

 

 2.3.1 实体类Category

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;}

2.3.2 CategoryMapper

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<Category> {
}

2.3.3 CategoryService

package com.runa.reggie.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Category;public interface CategoryService extends IService<Category> {
}

2.3.4 CategoryServiceImpl

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<CategoryMapper, Category> implements CategoryService {
}

2.3.5 CategoryController

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 {@Autowiredprivate CategoryService categoryService;
}

 

 2.3.6 CategoryController新增save方法

​
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 {@Autowiredprivate CategoryService categoryService;/*** 新增分类* @param category* @return*/@PostMappingpublic R<String> save(@RequestBody Category category){log.info("新增分类:{}", category);categoryService.save(category);return R.success("新增分类成功");}
}​

2.4 功能测试

 

三、分类信息分页查询

3.1 需求分析

 

3.2 代码实现

 3.2.1 CategoryController

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 {@Autowiredprivate CategoryService categoryService;/*** 新增分类* @param category* @return*/@PostMappingpublic R<String> save(@RequestBody Category category){log.info("新增分类:{}", category);categoryService.save(category);return R.success("新增分类成功");}/*** 分页查询* @param page* @param pageSize* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize){log.info("page= {}, pageSize= {}, name = {}",page, pageSize);//分页构造器Page pageInfo = new Page(page, pageSize);// 条件构造器LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();//添加排序条件,根据sort排序queryWrapper.orderByAsc(Category::getSort);//进行分页查询categoryService.page(pageInfo, queryWrapper);return R.success(pageInfo);}
}

3.2.1 Category注释是否删除字段

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;}

 

3.3 功能测试

 

四、删除分类

4.1 需求分析

 

4.2 代码实现

 4.2.1  CategoryController

注意传参是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 {@Autowiredprivate CategoryService categoryService;/*** 新增分类* @param category* @return*/@PostMappingpublic R<String> save(@RequestBody Category category){log.info("新增分类:{}", category);categoryService.save(category);return R.success("新增分类成功");}/*** 分页查询* @param page* @param pageSize* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize){log.info("page= {}, pageSize= {}, name = {}",page, pageSize);//分页构造器Page pageInfo = new Page(page, pageSize);// 条件构造器LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();//添加排序条件,根据sort排序queryWrapper.orderByAsc(Category::getSort);//进行分页查询categoryService.page(pageInfo, queryWrapper);return R.success(pageInfo);}/*** 根据id删除分类* @param ids* @return*/@DeleteMappingpublic R<String> delete(Long ids){log.info("根据ID删除分类:{}",ids);categoryService.removeById(ids);return R.success("分类信息删除成功");}
}

4.3 功能测试

 

4.4 功能完善

 4.4.1 菜品实体类Dish 

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;//菜品分类idprivate 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;}

4.4.2 套餐实体类Setmeal 

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;//分类idprivate 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;
}

 4.4.3 DishMapper 

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<Dish> {
}

4.4.4 SetmealMapper 

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<Setmeal> {
}

4.4.5 DishService 

package com.runa.reggie.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Dish;public interface DishService extends IService<Dish> {
}

 4.4.6 SetmealService 

package com.runa.reggie.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Setmeal;public interface SetmealService extends IService<Setmeal> {
}

4.4.7 DishServiceImpl 

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<DishMapper, Dish> implements DishService {
}

 4.4.8 SetmealServiceImpl 

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<SetmealMapper, Setmeal> implements SetmealService {
}

 4.4.9 修改CategoryService

package com.runa.reggie.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.runa.reggie.entity.Category;public interface CategoryService extends IService<Category> {public void remove(Long ids);
}

4.4.10  自定义业务异常类CustomException 

 

package com.runa.reggie.common;/*** 自定义业务异常类*/
public class CustomException extends RuntimeException {public CustomException(String message){super(message);}
}

4.4.11 CategoryServiceImpl 

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<CategoryMapper, Category> implements CategoryService {@Autowiredprivate DishService dishService;@Autowiredprivate SetmealService setmealService;@Overridepublic void remove(Long ids) {LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据分类id查询dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);int count1 = dishService.count(dishLambdaQueryWrapper);// 查询分类是否关联了菜品,如果关联了,抛出一个业务异常if(count1 > 0){// 关联了 抛出异常throw new CustomException("当前分类下关联了菜品,不能删除");}LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据分类id查询setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);int count2 = setmealService.count(setmealLambdaQueryWrapper);// 查询分类是否关联了套餐,如果关联了,抛出一个业务异常if(count2 > 0){// 关联了 抛出异常throw new CustomException("当前分类下关联了套餐,不能删除");}//执行删除super.removeById(ids);}
}

 4.4.12 GlobaExceptionHandler 

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<String> 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<String> exceptionHandler(CustomException ex){String msg = ex.getMessage();log.error(msg);return R.error(msg);}}

4.4.13 CategoryController 

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 {@Autowiredprivate CategoryService categoryService;/*** 新增分类* @param category* @return*/@PostMappingpublic R<String> save(@RequestBody Category category){log.info("新增分类:{}", category);categoryService.save(category);return R.success("新增分类成功");}/*** 分页查询* @param page* @param pageSize* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize){log.info("page= {}, pageSize= {}, name = {}",page, pageSize);//分页构造器Page pageInfo = new Page(page, pageSize);// 条件构造器LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();//添加排序条件,根据sort排序queryWrapper.orderByAsc(Category::getSort);//进行分页查询categoryService.page(pageInfo, queryWrapper);return R.success(pageInfo);}/*** 根据id删除分类* @param ids* @return*/@DeleteMappingpublic R<String> delete(Long ids){log.info("根据ID删除分类:{}",ids);
//        categoryService.removeById(ids);categoryService.remove(ids);return R.success("分类信息删除成功");}
}

 

 

五、修改分类

5.1 需求分析

 

5.2 代码实现

5.2.1 CategoryController

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 {@Autowiredprivate CategoryService categoryService;/*** 新增分类* @param category* @return*/@PostMappingpublic R<String> save(@RequestBody Category category){log.info("新增分类:{}", category);categoryService.save(category);return R.success("新增分类成功");}/*** 分页查询* @param page* @param pageSize* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize){log.info("page= {}, pageSize= {}, name = {}",page, pageSize);//分页构造器Page pageInfo = new Page(page, pageSize);// 条件构造器LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();//添加排序条件,根据sort排序queryWrapper.orderByAsc(Category::getSort);//进行分页查询categoryService.page(pageInfo, queryWrapper);return R.success(pageInfo);}/*** 根据id删除分类* @param ids* @return*/@DeleteMappingpublic R<String> delete(Long ids){log.info("根据ID删除分类:{}",ids);
//        categoryService.removeById(ids);categoryService.remove(ids);return R.success("分类信息删除成功");}@PutMappingpublic R<String> update(@RequestBody Category category){log.info("根据id更新分类信息:{}",category);categoryService.updateById(category);return R.success("修改分类信息成功");}
}

5.3 功能测试

 

相关文章:

【java】【项目实战】[外卖四]分类管理业务开发

前言&#xff1a;公共字段自动填充实现&#xff0c;删除业务逻辑实现 一、公共字段自动填充 1.1 问题分析 1.2 代码实现 1.2.1 修改实体类Employee package com.runa.reggie.entity;import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.…...

【Go 基础篇】Go语言包详解:模块化开发与代码复用

介绍 在Go语言中&#xff0c;包&#xff08;Package&#xff09; 是一种用于组织代码的机制&#xff0c;用于将相关的函数、类型和变量等组织在一起&#xff0c;以便于模块化开发和代码复用。包的使用能够使程序结构更加清晰、可维护性更高&#xff0c;同时也是Go语言强调的一…...

【业务功能篇82】微服务SpringCloud-ElasticSearch-Kibanan-docke安装-进阶实战

四、ElasticSearch进阶 https://www.elastic.co/guide/en/elasticsearch/reference/7.4/getting-started-search.html 1.ES中的检索方式 在ElasticSearch中支持两种检索方式 通过使用REST request URL 发送检索参数(uri检索参数)通过使用 REST request body 来发送检索参数…...

【工具】XML和JSON互相转换

1、JSON解析为XML function parseJSONToXML(json) {let xmlDoc document.implementation.createDocument(null, );function parseValue(value, parentElement) {if (Array.isArray(value)) {for (let item of value) {let arrayElement xmlDoc.createElement(parentElement.…...

前端面试:【浏览器与渲染引擎】Web APIs - DOM、XHR、Fetch、Canvas

嗨&#xff0c;亲爱的读者&#xff01;当我们在浏览器中浏览网页时&#xff0c;我们常常会与各种Web API打交道。这些API允许我们与网页内容、服务器资源和图形进行交互。本文将深入探讨一些常见的Web API&#xff0c;包括DOM、XHR、Fetch和Canvas&#xff0c;以帮助你了解它们…...

编码基础一:侵入式链表

一、简介概述 1、普通链表数据结构 每个节点的next指针指向下一个节点的首地址。这样会有如下的限制&#xff1a; 一条链表上的所有节点的数据类型需要完全一致。对某条链表的操作如插入&#xff0c;删除等只能对这种类型的链表进行操作&#xff0c;如果链表的类型换了&#…...

深圳IT行业供需:蓬勃发展的科技中心

深圳作为中国的科技中心之一&#xff0c;IT行业在这座城市蓬勃发展。本文将探讨深圳IT行业的供需状况&#xff0c;包括就业机会、技能需求以及行业前景展望。 近年来&#xff0c;深圳IT行业迅速发展&#xff0c;成为全球科技创新的重要枢纽之一。随着大量的科技企业和初创公司在…...

LeetCode 面试题 02.01. 移除重复节点

文章目录 一、题目二、C# 题解 一、题目 编写代码&#xff0c;移除未排序链表中的重复节点。保留最开始出现的节点。 点击此处跳转题目。 示例1: 输入&#xff1a;[1, 2, 3, 3, 2, 1] 输出&#xff1a;[1, 2, 3] 示例2: 输入&#xff1a;[1, 1, 1, 1, 2] 输出&#xff1a;[1, …...

【Java8特性】——Stream API

一、概述 <1> 是什么 是数据渠道&#xff0c;用于操作数据源&#xff08;集合、数组等&#xff09;所生成的元素序列。 Stream 不会存储数据Stream 不会改变数据源&#xff0c;相反&#xff0c;会返回一个持有结果的新Stream。Stream 操作是延迟执行的&#xff0c;这意…...

grep命令的用法

文章目录 前言一、使用说明二、应用举例 前言 grep 命令用于查找文件里符合条件的字符串。 一、使用说明 -r: 如果需要搜索目录中的文件内容, 需要进行递归操作, 必须指定该参数 -i: 对应要搜索的关键字, 忽略字符大小写的差别 -n: 在显示符合样式的那一行之前&#xff0c;标…...

【无标题】jenkins消息模板(飞书)

这里写目录标题 Jenkins 安装的插件 发送消息到飞书预览 1 &#xff08;单Job&#xff09;预览 2 &#xff08;多Job&#xff0c;概览&#xff09; Jenkins 安装的插件 插件名称作用Rebuilder Rebuilder。 官方地址&#xff1a;https://plugins.jenkins.io/rebuild 安装方式&a…...

2023年国赛 高教社杯数学建模思路 - 案例:随机森林

文章目录 1 什么是随机森林&#xff1f;2 随机深林构造流程3 随机森林的优缺点3.1 优点3.2 缺点 4 随机深林算法实现 建模资料 ## 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 什么是随机森林&#xff…...

element Collapse 折叠面板 绑定事件

1. 点击面板触发事件 change <el-collapse accordion v-model"activeNames" change"handleChange"><el-collapse-item title"一致性 Consistency"><div>与现实生活一致&#xff1a;与现实生活的流程、逻辑保持一致&#xff0c…...

CSS :mix-blend-mode、aspect-ratio

mix-blend-mode 元素的内容应该与元素的直系父元素的内容和元素的背景如何混合。 mix-blend-mode: normal; // 正常mix-blend-mode: multiply; // 正片叠底mix-blend-mode: screen; // 滤色mix-blend-mode: overlay; // 叠加mix-blend-mode: darken; // 变暗mix-blend-mode: …...

Module not found: Error: Can‘t resolve ‘less-loader‘解决办法

前言&#xff1a; 主要是在自我提升方面&#xff0c;感觉自己做后端还是需要继续努力&#xff0c;争取炮筒前后端&#xff0c;作为一个全栈软阿金开发人员&#xff0c;所以还是需要努力下&#xff0c;找个方面&#xff0c;目前是计划学会Vue&#xff0c;这样后端有java和pytho…...

量化QAT QLoRA GPTQ

模型量化的思路可以分为PTQ&#xff08;Post-Training Quantization&#xff0c;训练后量化&#xff09;和QAT&#xff08;Quantization Aware Training&#xff0c;在量化过程中进行梯度反传更新权重&#xff0c;例如QLoRA&#xff09;&#xff0c;GPTQ是一种PTQ的思路。 QAT…...

CentOS下查看 ssd 寿命

SSD写入量达到设计极限&#xff0c;颗粒擦写寿命耗尽后会导致磁盘写入速度非常缓慢&#xff0c;读取正常。 使用smartctl及raid卡管理软件查看硬盘smart信息可以发现Media_Wearout_Indicator值降为1&#xff0c;表明寿命完全耗尽。 涉及范围 所有SSD处理方案 查看SSD smart信…...

Node基础--npm相关内容

下面,我们一起来看看Node中的至关重要的一个知识点-----npm 1.npm概述 npm(Node Package Manager),CommonJS包规范是理论,npm是其中一种实践。 对于Node而言,NPM帮助其完成了第三方模块的发布、安装和依赖等。借助npm,Node与第三方模块之间形成了很好的一个 生态系统。(类…...

Python图片爬虫工具

不废话了&#xff0c;直接上代码&#xff1a; import re import os import requests import tqdmheader{User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36}def getImg(url,idx,path):imgre…...

制造执行系统(MES)在汽车行业中的应用

汽车行业在不断发展中仍然面临一些挑战和痛点。以下是一些当前汽车行业可能面临的问题&#xff1a; 1.电动化和可持续性转型&#xff1a;汽车行业正逐渐向电动化和可持续性转型&#xff0c;但这需要投入大量资金和资源&#xff0c;包括电池技术、充电基础设施等&#xff0c;同时…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

P3 QT项目----记事本(3.8)

3.8 记事本项目总结 项目源码 1.main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); } 2.widget.cpp #include "widget.h" #include &q…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序

一、开发环境准备 ​​工具安装​​&#xff1a; 下载安装DevEco Studio 4.0&#xff08;支持HarmonyOS 5&#xff09;配置HarmonyOS SDK 5.0确保Node.js版本≥14 ​​项目初始化​​&#xff1a; ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...

ServerTrust 并非唯一

NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...

3403. 从盒子中找出字典序最大的字符串 I

3403. 从盒子中找出字典序最大的字符串 I 题目链接&#xff1a;3403. 从盒子中找出字典序最大的字符串 I 代码如下&#xff1a; class Solution { public:string answerString(string word, int numFriends) {if (numFriends 1) {return word;}string res;for (int i 0;i &…...

sipsak:SIP瑞士军刀!全参数详细教程!Kali Linux教程!

简介 sipsak 是一个面向会话初始协议 (SIP) 应用程序开发人员和管理员的小型命令行工具。它可以用于对 SIP 应用程序和设备进行一些简单的测试。 sipsak 是一款 SIP 压力和诊断实用程序。它通过 sip-uri 向服务器发送 SIP 请求&#xff0c;并检查收到的响应。它以以下模式之一…...

MySQL 部分重点知识篇

一、数据库对象 1. 主键 定义 &#xff1a;主键是用于唯一标识表中每一行记录的字段或字段组合。它具有唯一性和非空性特点。 作用 &#xff1a;确保数据的完整性&#xff0c;便于数据的查询和管理。 示例 &#xff1a;在学生信息表中&#xff0c;学号可以作为主键&#xff…...

解析奥地利 XARION激光超声检测系统:无膜光学麦克风 + 无耦合剂的技术协同优势及多元应用

在工业制造领域&#xff0c;无损检测&#xff08;NDT)的精度与效率直接影响产品质量与生产安全。奥地利 XARION开发的激光超声精密检测系统&#xff0c;以非接触式光学麦克风技术为核心&#xff0c;打破传统检测瓶颈&#xff0c;为半导体、航空航天、汽车制造等行业提供了高灵敏…...

基于Uniapp的HarmonyOS 5.0体育应用开发攻略

一、技术架构设计 1.混合开发框架选型 &#xff08;1&#xff09;使用Uniapp 3.8版本支持ArkTS编译 &#xff08;2&#xff09;通过uni-harmony插件调用原生能力 &#xff08;3&#xff09;分层架构设计&#xff1a; graph TDA[UI层] -->|Vue语法| B(Uniapp框架)B --&g…...

简约商务通用宣传年终总结12套PPT模版分享

IOS风格企业宣传PPT模版&#xff0c;年终工作总结PPT模版&#xff0c;简约精致扁平化商务通用动画PPT模版&#xff0c;素雅商务PPT模版 简约商务通用宣传年终总结12套PPT模版分享:商务通用年终总结类PPT模版https://pan.quark.cn/s/ece1e252d7df...