St. Regis takeaway Day3 based on Springboot+MybatisPlus takeaway project

St. Regis Takeaway Day3

It is not easy to create, the code notes are all the understanding of personal learning, I hope everyone will like, follow and support

public field padding

1. Problem analysis

insert image description here

2. Implementation steps

1. Add the @TableField annotation to the attribute of the entity class to specify the automatic filling strategy
2. Write the metadata object processor according to the framework requirements, and assign values ​​to the public fields in this class. This class needs to implement the MetaObjectMapper interface

3. Code implementation

1. Add the following variables to the employee class
	@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. Create a new MyMetaObjectMapper class
package com.study.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 MyMetaObjectMapper implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段填充......");
        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", 1);
        metaObject.setValue("createUser", 1);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段填充......");
        log.info(metaObject.toString());
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("updateUser",1);
    }
}

Solve the fixed id

1. Problem analysis

We have completed the code development of the automatic filling function of public fields before, but there is still a problem that has not been solved, that is, the user id we set when automatically filling createUser and updateUser is a fixed value, and now we need to transform it to dynamically obtain the current login user. id. Some students may think that after the user logs in successfully, we store the user id in the HttpSession. Now I can get it from the HttpSession?
Note that we cannot obtain the HttpSession object in the MyMetaObjectMapper class, so we need to obtain the login user id in other ways.
You can use ThreadLocal to solve this problem, which is a class provided in JDK.
insert image description here

2. What is ThreadLocal?

​ThreadLocal is not a Thread, but a local variable of Thread . When using ThreadLocal to maintain variables, ThreadLocal provides an independent copy of the variable for each thread that uses the variable, so each thread can change its own copy independently without affecting the corresponding copies of other threads. ThreadLocal provides a separate storage space for each thread, which has the effect of thread isolation. The corresponding value can only be obtained within the thread, and cannot be accessed outside the thread.

​ThreadLocal common methods:
​ public void set(T value) Set the value of the thread local variable of the current thread
public T get() returns the value of the thread local variable corresponding to the current thread

3. Solutions

​ Obtain the current login user id in the doFilter method of LoginCheckFilter, and call the set method of ThreadLocal to set the value of the thread local variable (user id) of the current thread, and then call the get method of ThreadLocal in the updateFill method of MyMetaObjectHandler to obtain the current thread The value of the corresponding thread local variable (user id).

4. Implementation steps

1. Write the BaseContext tool class, based on the tool class encapsulated by ThreadLocal
2. Call BaseContext in the doFilter method of LoginCheckFilter to set the id of the currently logged-in user
3. Call BaseContext in the method of MyMetaObjectHandler to obtain the id of the logged-in user

5. Code implementation

1. Write the BaseContext tool class
package com.study.common;

/**
 * 基于ThreadLocal封装工具类,用户保存和获取当前id
 */
public class BaseContext {
    private static ThreadLocal<Long> threadLocal=new ThreadLocal<>();

    public static void setCurrentId(long id){
        threadLocal.set(id);
    }

    public static long getCurrentId(){
        return threadLocal.get();
    }
}
2. Call BaseContext to set the current user id

In the doFilter method of LoginCheckFilter

  //4、判断登录状态,如果已登录,则直接放行
        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. The MyMetaObjectMapper method calls BaseContext to obtain the id of the logged-in user
package com.study.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 MyMetaObjectMapper implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段填充......");
        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
        metaObject.setValue("createUser", BaseContext.getCurrentId());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段填充......");
        log.info(metaObject.toString());
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("updateUser",BaseContext.getCurrentId());
    }
}

Add category

First, the basic structure of classes and interfaces

  1. Entity class Category (import directly from the course materials)
  2. Mapper interface CategoryMapper
  3. Business layer interface CategoryService
  4. Business layer implementation class CategoryServiceimpl
  5. Control layer CategoryController

2. Code implementation

1. Import the Category class
package com.study.pojo;

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

}

2.Mapper interface CategoryMapper
package com.study.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.study.pojo.Category;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface CategoryMapper extends BaseMapper<Category> {
}

3. Service interface Category Service
package com.study.Service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.study.pojo.Category;

public interface CategoryService extends IService<Category> {
    public void remove(Long ids);
}

4. Service implementation class CategoryServiceimpl
package com.study.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.Service.CategoryService;
import com.study.Service.DishService;
import com.study.Service.SetmealService;
import com.study.common.CustomException;
import com.study.mapper.CategoryMapper;
import com.study.pojo.Category;
import com.study.pojo.Dish;
import com.study.pojo.Setmeal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CategoryServiceimpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类,删除之前需要进行判断
     * @param ids
     */
    @Override
    public 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);
    }
}

5.Controller control layer CategoryController
package com.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.Service.CategoryService;
import com.study.common.R;
import com.study.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

}

Category query

1. Problem analysis

2. Code implementation

Add the following method to the CategoryController class

 /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件,根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);

        //分页查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

delete category

1. Problem analysis

insert image description here

The function of deleting categories according to id does not check whether the deleted categories are associated with dishes or set meals. We need to improve the function.

2. Prepare basic classes and interfaces

  1. Entity classes Dish and Setmeal
  2. Mapper interface DishMapper and SetmealMapper
  3. Service interface DishService and SetmealService
  4. Service implementation classes DishServicelmpl and SetmealServicelmpl

3. Code implementation

1. Entity classes Dish and Setmeal
package com.study.pojo;

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;

}

package com.study.pojo;

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

2. Implement DishMapper and SetmealMapper interfaces
package com.study.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.study.pojo.Dish;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DishMapper extends BaseMapper<Dish> {
}

package com.study.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.study.pojo.Setmeal;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface SetmealMapper extends BaseMapper<Setmeal> {
    
    

}

3. Implement DishService and SetmealService interfaces
package com.study.Service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.study.pojo.Dish;

public interface DishService extends IService<Dish> {
    
    
   
}

package com.study.Service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.study.Dto.SetmealDto;
import com.study.pojo.Setmeal;

import java.util.List;

public interface SetmealService extends IService<Setmeal> {
    
    
}

4. Write DishServicelmpl and SetmealServicelmpl implementation classes
package com.study.Service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.Service.DishService;
import com.study.mapper.DishMapper;
import com.study.pojo.Dish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DishServiceimpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    
    
}

package com.study.Service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.Service.SetmealDishService;
import com.study.mapper.SetmealDishMapper;
import com.study.pojo.SetmealDish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SetmealDishServiceimpl extends ServiceImpl<SetmealDishMapper, SetmealDish> implements SetmealDishService {
    
    
}

5. New method of CategoryController class
/**
     * 根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
    
    
        log.info("删除分类,id为:{}",ids);

        categoryService.removeById(ids);
      //  categoryService.remove(id);

        return R.success("分类信息删除成功");
    }

modify classification

Modifying a category is similar to adding a category code

 /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
    
    
        log.info("修改分类信息:{}",category);

        categoryService.updateById(category);

        return R.success("修改分类信息成功");
    }

Guess you like

Origin blog.csdn.net/2201_75381449/article/details/129778093