基于Springboot+MybatisPlus的外卖项目瑞吉外卖Day3

Posted 小小程序○

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Springboot+MybatisPlus的外卖项目瑞吉外卖Day3相关的知识,希望对你有一定的参考价值。

瑞吉外卖Day3

创造实属不易,代码笔记全是个人学习的理解,希望大家点赞关注支持一下

公共字段填充

一、问题分析

二、实现步骤

1、在实体类的属性上加入@TableField注解,指定自动填充的策略
2、按照框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectMapper接口

三、代码实现

1.employee类添加如下变量
	@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.新建MyMetaObjectMapper类
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);
    

解决id固定

一、问题分析

前面我们已经完成了公共字段自动填充功能的代码开发,但是还有一个问题没有解决,就是我们在自动填充createUser和updateUser时设置的用户id是固定值,现在我们需要改造成动态获取当前登录用户的id。有的同学可能想到,用户登录成功后我们将用户id存入了HttpSession中,现在我从HttpSession中获取不就行了?
注意,我们在MyMetaObjectMapper类中是不能获得HttpSession对象的,所以我们需要通过其他方式来获取登录用户id。
可以使用ThreadLocal来解决此问题,它是JDK中提供的一个类。

二、什么是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封装的工具类
2、在LoginCheckFilter的doFilter方法中调用BaseContext来设置当前登录用户的id
3、在MyMetaObjectHandler的方法中调用BaseContext获取登录用户的id

五、代码实现

1.编写BaseContext工具类
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.调用BaseContext设置当前用户id

在LoginCheckFilter的doFilter方法中

  //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.MyMetaObjectMapper方法调用BaseContext获取登录用户的id
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());
    

新增分类

一、类和接口基本结构

  1. 实体类Category(直接从课程资料中导入即可)
  2. Mapper接口CategoryMapper
  3. 业务层接口CategoryService
  4. 业务层实现类CategoryServiceimpl
  5. 控制层CategoryController

二、代码实现

1.导入Category类
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接口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接口CategoryService
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实现类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控制层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("新增分类成功");
    



分类查询

一、问题分析

二、代码实现

CategoryController类中增加以下方法

 /**
     * 分页查询
     * @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);
    

删除分类

一、问题分析

根据id删除分类的功能,并没有检查删除的分类是否关联了菜品或者套餐,我们需要进行功能完善。

二、准备基础的类和接口

  1. 实体类Dish和Setmeal
  2. Mapper接口DishMapper和SetmealMapper
  3. Service接口DishService和SetmealService
  4. Service实现类DishServicelmpl和SetmealServicelmpl

三、代码实现

1.实体类Dish和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.实现DishMapper和SetmealMapper接口
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.实现DishService和SetmealService接口
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.编写DishServicelmpl和SetmealServicelmpl实现类
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.CategoryController类新增方法
/**
     * 根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids)
        log.info("删除分类,id为:",ids);

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

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

修改分类

修改分类跟新增分类代码类似

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

        categoryService.updateById(category);

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

基于SpringBoot的MybatisPlus简明教程

引言

互联网上已经存在了海量的基于SpringBoot的MybatisPlus教程,为什么还要创作本系列文章?

主要原因在于互联网上现有的关于Mybatis Plus的单篇文章关注的内容太多,过于复杂,不利于初学者快速入门,抓住问题的核心。

目标

本文的目标是:

  • 快速搭建基于SpringBoot的Mybatis-Plus非WEB的命令行开发环境;
  • 能够查询并显示数据库中用户表的所有数据;

方法

  • 创建数据库和项目所需表;

-- ----------------------------
-- Table structure for t_users
-- ----------------------------
DROP TABLE IF EXISTS `t_users`;
CREATE TABLE `t_users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of t_users
-- ----------------------------
INSERT INTO `t_users` VALUES ('1', 'abc', '123');
  • Idea中创建Maven项目;
  • pom.xml文件中添加项目所需依赖,并刷新Maven依赖;
    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
  • 创建数据库表对应的实体类;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("t_users")
public class UserEntity 
    private Long id;
    private String username;
    private String password;

  • 创建实体类对应的mapper类;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.sctu.demo.mybatis.plus.model.UserEntity;

public interface UserMapper extends BaseMapper<UserEntity> 

  • 进行MybatisPlus相关配置;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("edu.sctu.demo.mybatis.plus.mapper")
public class MybatisPlusConfig 

此处只需要配置mapper类的包路径即可;

  • 编写SpringBoot启动类,并进行测试;

@SpringBootApplication
public class Application implements CommandLineRunner 

    @Autowired(required = false)
    private UserMapper userMapper;

    public static void main(String[] args) 
        SpringApplication.run(Application.class, args);
    


    @Override
    public void run(String... args) throws Exception 
        System.out.println(userMapper.selectList(null));

    


  • 测试结果如下所示:

  .   ____          _            __ _ _
 /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
 \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.1)

2021-12-23 17:18:19.196  INFO 5996 --- [           main] edu.sctu.demo.mybatis.plus.Application   : Starting Application using Java 1.8.0_131 on WIN-K5EIUKCMVNI with PID 5996 (E:\\123\\sctu-tools-java\\mybatis-plus-demo\\target\\classes started by Administrator in E:\\123\\sctu-tools-java)
2021-12-23 17:18:19.198  INFO 5996 --- [           main] edu.sctu.demo.mybatis.plus.Application   : No active profile set, falling back to default profiles: default
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\\/|_)(_| | |_\\  |_)||_|_\\ 
     /               |         
                        3.4.3.4 
2021-12-23 17:18:20.238  INFO 5996 --- [           main] edu.sctu.demo.mybatis.plus.Application   : Started Application in 1.447 seconds (JVM running for 1.977)
2021-12-23 17:18:20.267  INFO 5996 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-12-23 17:18:20.594  INFO 5996 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
[UserEntity(id=1, username=abc, password=123)]
2021-12-23 17:18:20.638  INFO 5996 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-12-23 17:18:20.640  INFO 5996 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

结语

本文展示了SpringBoot整合MybatisPlus所需要的最少代码,可以帮助初学者快速入门。

以上是关于基于Springboot+MybatisPlus的外卖项目瑞吉外卖Day3的主要内容,如果未能解决你的问题,请参考以下文章

MybatisPlus——入门案例

基于SpringBoot+MyBatisPlus实现一套后台开发框架

基于Springboot+MybatisPlus的外卖项目瑞吉外卖Day3

基于Springboot和MybatisPlus的外卖项目 瑞吉外卖Day4

SpringBoot+MybatisPlus+Mysql+Sharding-JDBC分库分表实践

spring boot + MyBatisPlus 一对多、多对一、多对多的解决方案