苍穹外卖--新增员工

news/2024/7/23 15:27:35 标签: java, servlet, 开发语言

代码开发

package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增员工")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        log.info("新增员工{}", employeeDTO);
        employeeService.save(employeeDTO);
        return Result.success();
    }
}
package com.sky.service;

import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;

public interface EmployeeService {


    /**
     * 新增员工
     * @param employeeDTO
     */
    void save(EmployeeDTO employeeDTO);
}
package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

//        对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

//        设置账号状态,默认正常状态,1表示正常0表示禁用
        employee.setStatus(StatusConstant.ENABLE);

//        设置密码,默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        设置创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

//        设置创建人id和修改人id
//        TODO 后期需要修改为当前登录用户的id
        employee.setCreateUser(10L);
        employee.setUpdateUser(10L);

        employeeMapper.insert(employee);
    }

}
package com.sky.mapper;

import com.sky.entity.Employee;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface EmployeeMapper {


    /**
     * 插入员工数据
     * @param employee
     */
    @Insert("insert into employee (name, username, password, phone, sex, id_number, status,"+
            "create_time, update_time, create_user, update_user) "+
            "values (#{name},#{username},#{password},#{phone},#{sex},#{idNumber},#{status},"+
            "#{createTime},#{updateTime},#{createUser},#{updateUser})")
    void insert(Employee employee);
}

功能测试

开发阶段,后端测试主要以接口文档测试为主。

先获得登录令牌:

通过接口文档测试

通过前后端联调测试

代码完善

程序存在问题

1、录入的用户名已存在,抛出异常后没有处理

2、新增员工时,创建人id和修改人id设置为了固定值

处理

抛出异常

1、先发现异常:把已存在的用户名,在重新发送。

        idea显示错误

java.sql.SQLIntegrityConstraintViolationException: 
Duplicate entry 'zhangsan' for key 'idx_username'

2、在全局异常处理器中添加该异常

package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器,处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理sql重复存在名异常
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
//        Duplicate entry 'zhangsan' for key 'idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
//            获取用户名
            String username = split[2];
//          String msg = username + "已存在";
            String msg = username + MessageConstant.ALREDY_EXISTS;
            return Result.error(msg);
        }else {
//          未知错误
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

    }

}

设置创建人id和修改人id

ThreadLocal 并不是一个Thread,而是Thread的局部变量。 ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。

ThreadLocal常用方法:

public void set(T value)     设置当前线程的线程局部变量的值

public T get()         返回当前线程所对应的线程局部变量的值

public void remove()        移除当前线程的线程局部变量

package com.sky.context;

public class BaseContext {

    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

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

    public static Long getCurrentId() {
        return threadLocal.get();
    }

    public static void removeCurrentId() {
        threadLocal.remove();
    }

}

        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());


http://www.niftyadmin.cn/n/5546515.html

相关文章

理解SCI文件:EtherCAT子设备固定配置的关键

理解SCI文件&#xff1a;EtherCAT子设备固定配置的关键 在工业自动化和控制系统中&#xff0c;EtherCAT&#xff08;Ethernet for Control Automation Technology&#xff09;是一种广泛使用的高速通信协议。为了确保EtherCAT子设备&#xff08;SubDevice&#xff09;能够稳定…

Mysql系列-Binlog主从同步

原文链接&#xff1a;https://zhuanlan.zhihu.com/p/669450627 一、主从同步概述 mysql主从同步&#xff0c;即MySQL Replication,可以实现将数据从一台数据库服务器同步到多台数据库服务器。MySQL数据库自带主 从同步功能&#xff0c;经过配置&#xff0c;可以实现基于库、表…

工作手机监管系统销售防飞单保护企业资源

在竞争激烈的市场环境中&#xff0c;企业的每一笔交易都承载着发展的希望与未来的蓝图。然而&#xff0c;飞单现象如同暗流涌动&#xff0c;悄然侵蚀着企业的利润根基&#xff0c;威胁着团队的凝聚力与客户的信任。为了构建更加稳固的业务防线&#xff0c;我们隆重介绍——百川…

8-选择静态或共享库

在本节中&#xff0c;我们将展示如何使用BUILD_SHARED_LIBS变量来控制add_library()的默认行为&#xff0c;并允许控制如何构建没有显式类型的库(STATIC、SHARED、MODULE或OBJECT)。 要做到这一点&#xff0c;我们需要将BUILD_SHARED_LIBS添加到顶级的CMakeLists.txt中。我…

使用各向异性滤波器和图像处理方法进行脑肿瘤检测(MATLAB)

医学图像分割一直以来都是计算机辅助诊断领域的研究热点。在医学图像的处理和分析中&#xff0c;对图像中感兴趣区域的准确分割尤其关键。要对感兴趣区域进行分类识别&#xff0c;首先要从图像中把感兴趣区域精确分割出来&#xff0c;然后有针对性地对感兴趣区域提取特征并分类…

赠你一只金色的眼 - 富集分析和表达数据可视化

GOplot包介绍 GOplot包用于生物数据的可视化。更确切地说&#xff0c;该包将表达数据与功能分析的结果整合并进行可视化。但是要注意该包不能用于执行这些分析&#xff0c;只能把分析结果进行可视化。在所有科学领域&#xff0c;由于空间限制和结果所需的简洁性&#xff0c;切…

Navicat和MySQL的安装

1、下载 Navicat Navicat 官网&#xff1a;www.navicat.com.cn/ 在产品中可以看到很多的产品&#xff0c;点击免费试用 Navicat Premium 即可&#xff0c;是一套多连数据库开发工具&#xff0c;其他的只能连接单一类型数据库 点击试用 选择系统直接下载 二、安装 Navicat 安…

谷粒商城学习笔记-使用renren-fast-vue框架时安装依赖包遇到的问题及解决策略

文章目录 1&#xff0c;npm error Class extends value undefined is not a constuctor or null2&#xff0c;npm warn cli npm v10.8.1 does not support Node.js v16.20.2.3&#xff0c;npm error code CERT_HAS_EXPIRED学习心得 这篇文章记录下使用renren-fast-vue&#xff…