欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

编号功能

程序员文章站 2022-07-14 21:35:10
...

基础知识:相关注解:
@RequestBody(required = true) 这个注解一般就是前端需要传入一个对象
@RequestParam(required = true)这个注解一般就是前端需要传入某些字段
业务需求:自定义编码规则.设计一个由 前缀+后缀+时间戳+序列前置字符+自增序列 组成的编号规则,时间戳的位置可变.
涉及的数据库表有hr_serial_num_info------编码信息表;hr_serial_num_relation------编码关联表;sequence------自增序号表;
项目层级结构:
编号功能

接口:增删改查:

1.编号信息新增修改
(1)controller层 ----SerialNumRestController

/**
 1. 编号信息新增/修改
 2.  3. @param serialNumInfo
 4. @return
 */
@PostMapping(value = "/doSave")
@ApiOperation(value = "新增/修改编号信息")
@ApiImplicitParam(value = "编号信息DTO", name = "serialNumInfo")
@ResponseBody
public ResponseMessage doSave(@RequestBody(required = true) SerialNumInfoDTO serialNumInfo) {
    /* try {*/
    return serialNumService.doSave(serialNumInfo);
   /* } catch (Exception e) {
        return Result.error("操作失败");
    }
    */
}

(2)service层----SerialNumServicel 我把逻辑代码都放到了这个service实现类中

/**
 * 编号信息新增/修改
 * @param serialNumInfoDTO
 * @return
 */
ResponseMessage doSave(SerialNumInfoDTO serialNumInfoDTO);

service层----SerialNumInfoService

public interface SerialNumInfoService extends IService<SerialNumInfoModel>{
}

(3)service层实现类
SerialNumServiceImpl

/**
     * 编号信息新增/修改
     *
     * @param serialNumInfoDTO
     * @return
     */
    @Override
    public ResponseMessage doSave(SerialNumInfoDTO serialNumInfoDTO) {
        //创建一个infomodel对象,用来向数据库存入数据
        SerialNumInfoModel serialNumInfoModel = new SerialNumInfoModel();
        //调用corvet方法,转存数据
        corvet(serialNumInfoDTO, serialNumInfoModel);//调用corvet方法,转存数据
        BeanUtils.copyProperties(serialNumInfoDTO, serialNumInfoModel);
        //判断info表中Id是否已经存在
        if (StringUtils.isEmpty(serialNumInfoModel.getId())) {
            //数据库编号加了索引,判断编号是否重复
            try {
                //id不存在,新增编号信息
                infoService.save(serialNumInfoModel);
                return ResponseMessage.ok("新增成功");
            } catch (DuplicateKeyException exception) {
                return ResponseMessage.error("编号已存在,请重新输入");
            }
        }
        //id 已存在时,修改编号信息
        else {
            infoService.updateById(serialNumInfoModel);
            return ResponseMessage.ok("修改成功");
        }
    }
    //此方法用来转存数据,在编号新增接口中有调用
    private void corvet(SerialNumInfoDTO serialNumInfoDTO, SerialNumInfoModel serialNumInfoModel) {
        serialNumInfoModel.setCode(serialNumInfoDTO.getCode());
        serialNumInfoModel.setName(serialNumInfoDTO.getName());
        serialNumInfoModel.setPreString(serialNumInfoDTO.getPreString());
        serialNumInfoModel.setLastString(serialNumInfoDTO.getLastString());
        serialNumInfoModel.setTimeFormat(serialNumInfoDTO.getTimeFormat());
        serialNumInfoModel.setTimeLocation(serialNumInfoDTO.getTimeLocation());
    }

SerialNumInfoServiceImpl 这里的继承是mybatisPlus的特性,封装了一些基本的方法.(不知道理解的对不对)

@Service
@Slf4j
public class SerialNumInfoServiceImpl extends ServiceImpl<ServialNumInfoMapper, SerialNumInfoModel> implements SerialNumInfoService {
}

(4)Mapper层,也用到了mybatisPlus的简化

@Mapper
public interface ServialNumInfoMapper extends BaseMapper<SerialNumInfoModel> {
   /* List<Map<String, Object>> selectByCode(String code);*/
}

(5)DTO层,这一层就是对外暴露的一些字段,然后不能和数据库字段一致,会有安全问题.这层就不贴代码了.至此,编号的新增修改接口就完成了.

2.创建编号关联对象
(1)controller 层-----SerialNumRestController

 /**
     * 创建编号对象关联
     *
     * @param serialNumRelationDTO
     * @return
     */
    @PostMapping(value = "/createRelation")
    @ApiOperation(value = "创建编号对象关联")
    @ApiImplicitParam(value = "编号对象关联DTO", name = "serialNumRelation")
    @ResponseBody
    public ResponseMessage createRelation(@RequestBody(required = true) SerialNumRelationDTO serialNumRelationDTO) {
        return serialNumService.createRelation(serialNumRelationDTO);
    }

(2)service层-下面的service层代码不再说明在哪个类中

----SerialNumServicel

/**
	 * 创建编号对象关联
	 * @param serialNumRelationDTO
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> createRelation(SerialNumRelationDTO serialNumRelationDTO);

----SerialNumRelationService

public interface SerialNumRelationService extends IService<SerialNumRelationModel>{
}

(3)service层实现类

这里的业务逻辑相对多一些,需要多思考

/**
     * 创建/修改编号对象关联
     *
     * @param serialNumRelationDTO
     * @return
     */
    @Override
    public ResponseMessage createRelation(SerialNumRelationDTO serialNumRelationDTO) {
        //创建一个relationModel 对象,用来接DTO传过来的数据
        SerialNumRelationModel serialNumRelationModel = new SerialNumRelationModel();
        //创建sequence对象,往sequence表中加数据
        SequenceModel sequenceModel = new SequenceModel();
        //将dto的数据存到entity中
        BeanUtils.copyProperties(serialNumRelationDTO, serialNumRelationModel);
        serialNumRelationModel.setSerialId(serialNumRelationDTO.getSerialNumInfo().getId());
        //往sequence中加数据
        sequenceModel.setName(serialNumRelationDTO.getSequenceName());
        sequenceModel.setCurrentValue(serialNumRelationDTO.getStartNum());
        //数据库中给code 加了唯一索引,在这里是把id唯一作为条件
        if (StringUtils.isEmpty(serialNumRelationModel.getId())){
            try {
                //id不存在,新增编号关联信息和初始序号
                relationService.save(serialNumRelationModel);
                sequenceService.save(sequenceModel);
                return ResponseMessage.ok("新增成功");
            } catch (DuplicateKeyException exception) {
                return ResponseMessage.error("编号关联已存在,请重新输入");
            }
        }
        //id 已存在时,修改编号关联信息
        else {
            relationService.updateById(serialNumRelationModel);
            return ResponseMessage.ok("修改成功");
        }
        }

另一个service层实现类以及mapper层参考上面infoservice的实现类.

以下的接口代码放到一起介绍:代码全选粘过来的,会有上面的重复代码.

controller层

package org.hrvc.modules.serialnum.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hrvc.common.api.vo.ResponseMessage;
import org.hrvc.modules.serialnum.dto.SerialNumInfoDTO;
import org.hrvc.modules.serialnum.dto.SerialNumRelationDTO;
import org.hrvc.modules.serialnum.service.SerialNumRelationService;
import org.hrvc.modules.serialnum.service.SerialNumServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author dongxiaomeng
 * @description controller
 * @since 2020/11/16
 */
@Api(value = "编号生成接口", tags = {"编号操作接口"})
@RestController
@RequestMapping("/test/serialNum")
@Slf4j

public class SerialNumRestController {
    @Autowired
    private SerialNumServiceI serialNumService;
    /**
     * 编号列表页
     *
     * @return
     */
    @PostMapping(value = "/getList")
    @ApiOperation(value = "编号信息列表")
    @ResponseBody
    public ResponseMessage<List<SerialNumInfoDTO>> getList(@RequestBody(required = true) SerialNumInfoDTO serialNumInfo) {

        /*return serialNumService.getRelationList(serialId);*/
        return serialNumService.getList(serialNumInfo);
    }

    /**
     * 编号信息新增/修改
     *
     * @param serialNumInfo
     * @return
     */
    @PostMapping(value = "/doSave")
    @ApiOperation(value = "新增/修改编号信息")
    @ApiImplicitParam(value = "编号信息DTO", name = "serialNumInfo")
    @ResponseBody
    public ResponseMessage doSave(@RequestBody(required = true) SerialNumInfoDTO serialNumInfo) {
        /* try {*/
        return serialNumService.doSave(serialNumInfo);
       /* } catch (Exception e) {
            return Result.error("操作失败");
        }
        */
    }

    /**
     * 根据主键id获取编号信息详情
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/getDetail")
    @ApiOperation(value = "根据主键id获取编号信息详情")
    @ApiImplicitParam(value = "主键id", name = "id")
    @ResponseBody
    public ResponseMessage<SerialNumInfoDTO> getDetail(@RequestParam(required = true) String id) {
        return serialNumService.getDetail(id);
    }

    /**
     * 编号信息状态变更
     *
     * @param id
     * @param status
     */
    @PostMapping(value = "/changeStatus")
    @ApiOperation(value = "编号信息状态变更")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "主键id", name = "id"),
            @ApiImplicitParam(value = "状态", name = "status")
    })
    @ResponseBody
    public ResponseMessage<SerialNumInfoDTO> changeStatus(@RequestParam(required = true) String id, @RequestParam(required = true) int status) {
        //返回对象,
        ResponseMessage<SerialNumInfoDTO> result = serialNumService.getDetail(id);
        //判断返回
        if (null == result.getResult()) {
            return ResponseMessage.error("未找到编号信息");
        }
        try {
            serialNumService.changeStatus(id, status);

        } catch (Exception ex) {
            return ResponseMessage.error("系统异常,请稍后重试");
        }
        return result;
    }

    /**
     * 编号信息删除
     *
     * @param id
     */
    @PostMapping(value = "/update")
    @ApiOperation(value = "编号信息删除")
    @ApiImplicitParam(value = "主键id", name = "id")
    @ResponseBody
    public ResponseMessage<SerialNumInfoDTO> doDelet(@RequestParam(required = true) String id) {
        ResponseMessage<SerialNumInfoDTO> result = serialNumService.getDetail(id);
        if (null == result.getResult()) {
            return ResponseMessage.error("未找到编号信息");
        }
        try {
            serialNumService.doDelete(id);
        } catch (Exception ex) {
            //日志
            //log.error("doDelete id={}, e={}", deleteFlag, ex);
            return ResponseMessage.error("系统异常,请稍后重试");
        }
        return ResponseMessage.ok();
    }

    /**
     * 创建编号对象关联
     *
     * @param serialNumRelationDTO
     * @return
     */
    @PostMapping(value = "/createRelation")
    @ApiOperation(value = "创建编号对象关联")
    @ApiImplicitParam(value = "编号对象关联DTO", name = "serialNumRelation")
    @ResponseBody
    public ResponseMessage createRelation(@RequestBody(required = true) SerialNumRelationDTO serialNumRelationDTO) {
        return serialNumService.createRelation(serialNumRelationDTO);
    }

    /**
     * 编号对象关联列表
     *
     * @return
     */
    @PostMapping(value = "/getRelationList")
    @ApiOperation(value = "获取编号对象关联列表")
    @ResponseBody
    public ResponseMessage<List<SerialNumRelationDTO>> getRelationList(String serialId) {
        return serialNumService.getRelationList(serialId);
    }

    /**
     * 获取编号对象关联详情
     *
     * @param id SerialNumInfo主键id
     * @return
     */
    @PostMapping(value = "/getRelationDetail")
    @ApiOperation(value = "获取编号对象关联详情")
    @ApiImplicitParam(value = "主键id", name = "id")
    @ResponseBody
    public ResponseMessage<SerialNumRelationDTO> getRelationDetail(@RequestParam(required = true) String id) {
        return serialNumService.getRelationDetail(id);
    }

    /**
     * 获取当前编号
     *
     * @param relationObj 关联对象
     * @param serialCode  SerialNumInfo唯一标识code
     * @return
     */
    @PostMapping(value = "/getCurrentNum")
    @ApiOperation(value = "获取当前编号")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "关联对象字符串", name = "relationObj"),
            @ApiImplicitParam(value = "编号信息编码", name = "serialCode")
    })
    @ResponseBody
    public ResponseMessage getCurrentNum(@RequestParam(required = true) String relationObj, @RequestParam(required = true) String serialCode) {

        return serialNumService.getCurrentNum(relationObj, serialCode);
    }

    /**
     * 获取下一个编号
     *
     * @param relationObj 关联对象
     * @param serialCode  SerialNumInfo唯一标识code
     * @return
     */
    @PostMapping(value = "/getNextNum")
    @ApiOperation(value = "获取下一个编号")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "关联对象字符串", name = "relationObj"),
            @ApiImplicitParam(value = "编号信息编码", name = "serialCode")
    })
    @ResponseBody
    public ResponseMessage getNextNum(@RequestParam(required = true) String relationObj, @RequestParam(required = true) String serialCode) {
        return serialNumService.getNextNum(relationObj, serialCode);
    }

    /**
     * 编号回退
     *
     * @param relationObj 编号回退
     * @param serialCode  SerialNumInfo唯一标识code
     * @param step        回退步长
     */
    @PostMapping(value = "/fallbackNum")
    @ApiOperation(value = "编号回退")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "关联对象字符串", name = "relationObj"),
            @ApiImplicitParam(value = "编号信息编码", name = "serialCode"),
            @ApiImplicitParam(value = "回退步长", name = "step")
    })
    @ResponseBody
    public ResponseMessage<SerialNumRelationDTO> fallbackNum(@RequestParam(required = true) String relationObj, @RequestParam(required = true) String serialCode, @RequestParam(required = true) int step) {
        return serialNumService.fallbackNum(relationObj, serialCode, step);
    }

    /**
     * 归零
     */
    @PostMapping(value = "/returnToZero")
    @ApiOperation(value = "归零")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "归零", name = "serialNumRelation")
    })
    @ResponseBody
    public ResponseMessage retToZero(@RequestBody(required = true) SerialNumRelationDTO serialNumRelationDTO) {
        return serialNumService.retToZero(serialNumRelationDTO);
    }
}

service层,带有业务逻辑的service

public interface SerialNumServiceI    {
	/**
	 * 编号信息新增/修改
	 * @param serialNumInfoDTO
	 * @return
	 */
	ResponseMessage doSave(SerialNumInfoDTO serialNumInfoDTO);
	/**
	 * 根据主键id获取编号信息详情
	 * @param id
	 * @return
	 */
	ResponseMessage<SerialNumInfoDTO> getDetail(String id);
	/**
	 * 编号信息列表
	 * @return
	 */
	ResponseMessage<List<SerialNumInfoDTO>> getList(SerialNumInfoDTO serialNumInfoDTO);
	/**
	 * 编号信息状态变更
	 * @param id
	 * @param status
	 */
	void changeStatus(String id, int status);
	/**
	 * 编号信息删除
	 * @param id
	 */
	void doDelete(String id);
	/**
	 * 创建编号对象关联
	 * @param serialNumRelationDTO
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> createRelation(SerialNumRelationDTO serialNumRelationDTO);
	/**
	 * 编号对象关联列表
	 * @param serialId
	 * @return
	 */
	ResponseMessage<List<SerialNumRelationDTO>> getRelationList(String serialId);
	/**
	 * 获取编号对象关联详情
	 * @param id SerialNumRelation主键id
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> getRelationDetail(String id);
	/**
	 * 获取当前编号
	 * @param relationObj 关联对象
	 * @param serialCode SerialNumInfo唯一标识code
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> getCurrentNum(String relationObj, String serialCode);
	/**
	 *  获取下一个编号
	 * @param relationObj 关联对象
	 * @param serialCode SerialNumInfo唯一标识code
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> getNextNum(String relationObj, String serialCode);
	/**
	 * 编号回退
	 * @param relationObj 关联对象
	 * @param serialCode SerialNumInfo唯一标识code
	 * @param step 回退步长
	 */
	ResponseMessage<SerialNumRelationDTO> fallbackNum(String relationObj, String serialCode, int step);
	/**
	 * 归零
	 * @param zeroCycle
	 * @return
	 */
	ResponseMessage<SerialNumRelationDTO> retToZero(SerialNumRelationDTO serialNumRelationDTO);
}

service的实现类—最重要的一个

package org.hrvc.modules.serialnum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.hrvc.common.api.vo.ResponseMessage;
import org.hrvc.common.api.vo.Result;
import org.hrvc.common.constant.CommonConstant;
import org.hrvc.common.util.DateUtils;
import org.hrvc.common.util.HRVCConverter;
import org.hrvc.common.util.StringUtils;
import org.hrvc.modules.serialnum.dto.SerialNumInfoDTO;
import org.hrvc.modules.serialnum.dto.SerialNumRelationDTO;
import org.hrvc.modules.serialnum.entity.SequenceModel;
import org.hrvc.modules.serialnum.entity.SerialNumInfoModel;
import org.hrvc.modules.serialnum.entity.SerialNumRelationModel;
import org.hrvc.modules.serialnum.mapper.SerivalNumMapper;
import org.hrvc.modules.serialnum.service.SequenceService;
import org.hrvc.modules.serialnum.service.SerialNumInfoService;
import org.hrvc.modules.serialnum.service.SerialNumRelationService;
import org.hrvc.modules.serialnum.service.SerialNumServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.management.relation.RelationService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 编号实现类
 * @Author: dongxaiomeng
 * @since: 2020/11/16
 * @Version: V1.0
 */

@Service
@Slf4j
public class SerialNumServiceImpl implements SerialNumServiceI {

    @Autowired
    private SerivalNumMapper serivalNumMapper;
    @Autowired
    private SerialNumRelationService relationService;
    @Autowired
    private SerialNumInfoService infoService;
    @Autowired
    private SequenceService sequenceService;

    /**
     * 编号信息新增/修改
     *
     * @param serialNumInfoDTO
     * @return
     */
    @Override
    public ResponseMessage doSave(SerialNumInfoDTO serialNumInfoDTO) {
        //创建一个infomodel对象,用来向数据库存入数据
        SerialNumInfoModel serialNumInfoModel = new SerialNumInfoModel();
        //调用corvet方法,转存数据
        corvet(serialNumInfoDTO, serialNumInfoModel);//调用corvet方法,转存数据
        BeanUtils.copyProperties(serialNumInfoDTO, serialNumInfoModel);
        //判断info表中Id是否已经存在
        if (StringUtils.isEmpty(serialNumInfoModel.getId())) {
            //数据库编号加了索引,判断编号是否重复
            try {
                //id不存在,新增编号信息
                infoService.save(serialNumInfoModel);
                return ResponseMessage.ok("新增成功");
            } catch (DuplicateKeyException exception) {
                return ResponseMessage.error("编号已存在,请重新输入");
            }
        }
        //id 已存在时,修改编号信息
        else {
            infoService.updateById(serialNumInfoModel);
            return ResponseMessage.ok("修改成功");
        }
    }

    //此方法用来转存数据,在编号新增接口中有调用
    private void corvet(SerialNumInfoDTO serialNumInfoDTO, SerialNumInfoModel serialNumInfoModel) {
        serialNumInfoModel.setCode(serialNumInfoDTO.getCode());
        serialNumInfoModel.setName(serialNumInfoDTO.getName());
        serialNumInfoModel.setPreString(serialNumInfoDTO.getPreString());
        serialNumInfoModel.setLastString(serialNumInfoDTO.getLastString());
        serialNumInfoModel.setTimeFormat(serialNumInfoDTO.getTimeFormat());
        serialNumInfoModel.setTimeLocation(serialNumInfoDTO.getTimeLocation());
    }

    /**
     * 编号信息删除
     *
     * @param id
     */
    @Override
    public void doDelete(String id) {
        //编号删除为逻辑删除,只是更改了del_flag字段的值,0代表未删除,1代表已删除,需要注意的是逻辑删除会影响查询方法,在查询编号信息的时候,需要把del_flag==1的编号信息过滤掉
        //这里用的是lambda表达式来做字段更改,在数据库中,给del_flag字段加了索引.
        infoService.update(new UpdateWrapper<SerialNumInfoModel>().lambda()
                .eq(SerialNumInfoModel::getId, id)
                .set(SerialNumInfoModel::getDeleteFlag, CommonConstant.DEL_FLAG_1));
    }

    /**
     * 根据主键id获取编号信息详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseMessage getDetail(String id) {
        //获取info表中的id,这里是精确查询
        SerialNumInfoModel serialNumInfoModel = infoService.getById(id);
        //创建一个DTO对象,用来传参
        SerialNumInfoDTO serialNumInfoDTO = new SerialNumInfoDTO();
        //把从数据库取出的值,传回DTO层,此处借用了杰哥的方法
        BeanCopier copier = BeanCopier.create(SerialNumInfoModel.class, SerialNumInfoDTO.class, true);
        copier.copy(serialNumInfoModel, serialNumInfoDTO, new HRVCConverter());
        //返回值
        return ResponseMessage.ok(serialNumInfoDTO);
    }

    /**
     * 编号信息列表
     */
    @Override
    public ResponseMessage<List<SerialNumInfoDTO>> getList(SerialNumInfoDTO serialNumInfoDTO) {
        //新建返回值对象
        ResponseMessage<List<SerialNumInfoDTO>> result = new ResponseMessage<List<SerialNumInfoDTO>>();
        //查询列表,条件用lambda筛选,like 模糊查询
        List<SerialNumInfoModel> modelList = infoService.list(new QueryWrapper<SerialNumInfoModel>()
                .lambda()
                //通过传进来的code查询
                .like(SerialNumInfoModel::getCode, serialNumInfoDTO.getCode())
                .or()
                //通过传进来的name查询
                .like(SerialNumInfoModel::getName, serialNumInfoDTO.getName())
        );
        //过滤deleteflag=1的编号信息
		/*List<SerialNumInfoModel> resultList = modelList.stream()
				.filter(serialNumInfoModel -> (serialNumInfoModel.getDeleteFlag()==1))
				.collect(Collectors.toList());*/
        //定义serialNumInfo,
        SerialNumInfoDTO serialNumInfo = null;
        //创建列表对象
        List<SerialNumInfoDTO> serialNumInfoList = new ArrayList<SerialNumInfoDTO>();
        //for循环用来干嘛的呢,就是取出列表,把数据库的每条信息赋给DTO取出来.
        for (SerialNumInfoModel model : modelList) {
            //用来接收数据库的信息的DTO层
            serialNumInfo = new SerialNumInfoDTO();
            //从数据库model赋值给dto
            BeanCopier copier = BeanCopier.create(SerialNumInfoModel.class, SerialNumInfoDTO.class, true);
            copier.copy(model, serialNumInfo, new HRVCConverter());
            serialNumInfoList.add(serialNumInfo);
        }
        //返回结果赋值
        result.setResult(serialNumInfoList);
        return result;
    }

    /**
     * 编号信息状态变更
     *
     * @param id
     * @param status
     */
    @Override
    //这个方法就是改变编号信息的状态,和它相关即要操作的字段就是info表的Status,0-抑制,1-启用,2-禁用
    public void changeStatus(String id, int status) {
        //根据id更新status的内容
        infoService.update(new UpdateWrapper<SerialNumInfoModel>().lambda()
                .eq(SerialNumInfoModel::getId, id)
                .set(SerialNumInfoModel::getStatus, status));
    }

    /**
     * 创建/修改编号对象关联
     *
     * @param serialNumRelationDTO
     * @return
     */
    @Override
    public ResponseMessage createRelation(SerialNumRelationDTO serialNumRelationDTO) {
        //创建一个relationModel 对象,用来接DTO传过来的数据
        SerialNumRelationModel serialNumRelationModel = new SerialNumRelationModel();
        //创建sequence对象,往sequence表中加数据
        SequenceModel sequenceModel = new SequenceModel();
        //将dto的数据存到entity中
        BeanUtils.copyProperties(serialNumRelationDTO, serialNumRelationModel);
        serialNumRelationModel.setSerialId(serialNumRelationDTO.getSerialNumInfo().getId());
        //往sequence中加数据
        sequenceModel.setName(serialNumRelationDTO.getSequenceName());
        sequenceModel.setCurrentValue(serialNumRelationDTO.getStartNum());
        //在这里是把id是否唯一作为判断条件,
        if (StringUtils.isEmpty(serialNumRelationModel.getId())) {
            try {
                //id不存在,新增编号关联信息和初始序号
                relationService.save(serialNumRelationModel);
                sequenceService.save(sequenceModel);
                return ResponseMessage.ok("新增成功");
            } catch (DuplicateKeyException exception) {
                return ResponseMessage.error("编号关联已存在,请重新输入");
            }
        }
        //id 已存在时,修改编号关联信息
        else {
            relationService.updateById(serialNumRelationModel);
            return ResponseMessage.ok("修改成功");
        }
    }
    /**
     * 编号对象关联列表
     *
     * @return
     */
    @Override
    public ResponseMessage<List<SerialNumRelationDTO>> getRelationList(String serialId) {
        //返回值
        ResponseMessage<List<SerialNumRelationDTO>> result = new ResponseMessage<List<SerialNumRelationDTO>>();
        //根据seralId得到relationModel
        List<SerialNumRelationModel> modelList = relationService.list(new QueryWrapper<SerialNumRelationModel>()
                .lambda()
                .eq(SerialNumRelationModel::getSerialId, serialId));
        //初始化DTO,返回值时要用
        SerialNumRelationDTO serialNumRelationDTO = null;
        //新建relationDTOList集合,用来存从数据库取出的数据
        List<SerialNumRelationDTO> serialNumRelationDTOList = new ArrayList<SerialNumRelationDTO>();
        //这个循环用来从数据库中取数据,存到dto中,但是未实现.
        //SerialNumInfoModel serialNumInfoModel = new SerialNumInfoModel();
        for (SerialNumRelationModel model : modelList) {
            //创建一个relationDTO对象,用来转存数据
            serialNumRelationDTO = new SerialNumRelationDTO();
            //从数据库取值赋值
            BeanCopier copier = BeanCopier.create(SerialNumRelationModel.class, SerialNumRelationDTO.class, true);
            copier.copy(model, serialNumRelationDTO, new HRVCConverter());
            serialNumRelationDTOList.add(serialNumRelationDTO);
        }
        //返回存储
        result.setResult(serialNumRelationDTOList);
        return result;
    }

    /**
     * 获取编号对象关联详情
     *
     * @param id SerialNumRelation主键id
     * @return
     */
    @Override
    public ResponseMessage getRelationDetail(String id) {
        //取出relation的id,精确查询
        SerialNumRelationModel serialNumRelationModel = relationService.getById(id);
        //创建一个DTO,用来将数据库取出的值传出来
        SerialNumRelationDTO serialNumRelationDTO = new SerialNumRelationDTO();
        //数据转换
        BeanCopier copier = BeanCopier.create(SerialNumRelationModel.class, SerialNumRelationDTO.class, true);
        copier.copy(serialNumRelationModel, serialNumRelationDTO, new HRVCConverter());
        return ResponseMessage.ok(serialNumRelationDTO);
    }

    /**
     * 根据relation,serialCode,从数据库取出sequenceName
     *
     * @param relationObj
     * @param serialCode
     * @return
     */
    private Map<String, Object> getSerialInfo(String relationObj, String serialCode) {
        //1.根据serialCode查询serialNumInfoModel
        SerialNumInfoModel serialNumInfoModel = infoService.getOne(new QueryWrapper<SerialNumInfoModel>()
                .lambda()
                //获取数据库中相等的code的数据
                .eq(SerialNumInfoModel::getCode, serialCode));
        //2. 根据relationObj和serialNumInfoModel.id 查询SerialNumRelationModel
        SerialNumRelationModel serialNumRelationModel = relationService.getOne(new QueryWrapper<SerialNumRelationModel>()
                .lambda()
                //通过上面的code找到info的id和relation中serival_id相等的关联表的relationobj,
                .eq(SerialNumRelationModel::getSerialId, serialNumInfoModel.getId())
                .eq(SerialNumRelationModel::getRelationObj, relationObj));
        //定义返回的result
        Map<String, Object> result = new HashMap<String, Object>();
        //把infomodel和relationmodel中的数据存储.
        result.put("serialNumInfoModel", serialNumInfoModel);
        result.put("serialNumRelationModel", serialNumRelationModel);
        return result;
    }

    /**
     * 根据传递的sequenceNum和serialNumInfoModel以及serialNumRelationModel 拼接编号字符串
     *
     * @param serialNumInfoModel
     * @param serialNumRelationModel
     * @param sequenceNum
     * @return
     */
    private String formatCodeNum(SerialNumInfoModel serialNumInfoModel, SerialNumRelationModel serialNumRelationModel, int sequenceNum) {
        //字符串类型,下面可用于数据类型转换成字符串
        String codeNumStr = "";
        // ${seq}前面的部分
        //获取自增序列的最大长度
        serialNumRelationModel.getSeqMaxlength();
        //获取是否补零
        serialNumRelationModel.getPadding();
	   /* if(sequenceNum % serialNumRelationModel.getSeqMaxlength()*10) {
		throw new Exception("超过最大长度,请检查配置");
	    }*/
        //获取数据库中的序列前置字符
        String seqNumCode = serialNumRelationModel.getSeqPre();//
        // 判断是否需要进行补0
        if (1 == serialNumRelationModel.getPadding()) {
            //zeroLen是数据库定义的序列最大长度-前端传过来的sequenceNum的长度值   String.valueOf(sequenceNum).length()
            int zeroLen = serialNumRelationModel.getSeqMaxlength() - String.valueOf(sequenceNum).length();
            //将sequenceNum转化为字符串
            String seqNumStr = String.valueOf(sequenceNum);
            //for循环,用来补零操作,条件为当
            for (int i = 0; i < zeroLen; i++) {
                seqNumStr = 0 + seqNumStr;
            }
            seqNumCode += seqNumStr;
        } else {
            seqNumCode += sequenceNum;
        }
        // ${seq}前面的部分
        //时间位置
        String str0 = "";//左
        String str1 = "";//中
        String str2 = "";//右
        // 没有时间输出
        if (!"无".equals(serialNumInfoModel.getTimeLocation()) && !"无".equals(serialNumInfoModel.getTimeFormat())) {
            // 有时间输出,则需要根据位置进行拼接
            String dateTimeStr = DateUtils.getDate(serialNumInfoModel.getTimeFormat());
            switch (serialNumInfoModel.getTimeLocation()) {
                case 1:
                    str0 = dateTimeStr;
                    break;
                case 2:
                    str1 = dateTimeStr;
                    break;
                case 3:
                    str2 = dateTimeStr;
                    break;
            }
        }
        //根据时间位置进行编号组合
        codeNumStr = str0 + serialNumInfoModel.getPreString() + str1 + serialNumInfoModel.getLastString() + str2;
        codeNumStr = codeNumStr + seqNumCode;
        return codeNumStr;
    }

    /**
     * 获取当前编号
     *
     * @param relationObj 关联对象
     * @param serialCode  SerialNumInfo唯一标识code
     * @return
     */
    @Override
    public ResponseMessage getCurrentNum(String relationObj, String serialCode) {

        //这是调用根据relationObj和serialCode获取数据库的值
        Map<String, Object> map = getSerialInfo(relationObj, serialCode);
        //根据第2步骤SerialNumRelationModel.sequenceName 执行函数currval(map.get("serialNumRelationModel").getSequence())
        //获取函数得到的当前序列
        int num = getCurrval(((SerialNumRelationModel) map.get("serialNumRelationModel")).getSequenceName());
        //强转获取infomodel
        SerialNumInfoModel serialNumInfoModel = (SerialNumInfoModel) map.get("serialNumInfoModel");
        //强转获取relationmodel
        SerialNumRelationModel serialNumRelationModel = (SerialNumRelationModel) map.get("serialNumRelationModel");
        if (serialNumRelationModel.getSeqMaxlength() >= String.valueOf(num).length()) {
            String code = formatCodeNum(serialNumInfoModel, serialNumRelationModel, num);
            //返回code
            return ResponseMessage.ok(code);
        } else {
            //当序号大于最大数时,取最大数,

            return ResponseMessage.error("当前序号不合规范,大于序号最大值");
        }
        //调用拼接编号的方法
        //String code = formatCodeNum(serialNumInfoModel, serialNumRelationModel, num);
        //返回code
        //  return ResponseMessage.ok(code);
    }

    //这是当前序列的函数调用方法,和mapper.xml层连接的方法
    private int getCurrval(String seqName) {
        int currentNum = serivalNumMapper.getCurrvalNum(seqName);
        return currentNum;
    }

    /**
     * 获取下一个编号
     *
     * @param relationObj 关联对象
     * @param serialCode  SerialNumInfo唯一标识code
     * @return
     */
    @Override
    public ResponseMessage getNextNum(String relationObj, String serialCode) {
        //从数据取值
        Map<String, Object> map = getSerialInfo(relationObj, serialCode);
        //3.根据第2步骤SerialNumRelationModel.sequenceName 执行函数nextval(map.get("serialNumRelationModel").getSequence())
        //函数取序号
        // int num = getNextNum(((SerialNumRelationModel) map.get("serialNumRelationModel")).getSequenceName());
        int num = getNextNum(((SerialNumRelationModel) map.get("serialNumRelationModel")).getSequenceName());
        //取infoModel
        SerialNumInfoModel serialNumInfoModel = (SerialNumInfoModel) map.get("serialNumInfoModel");
        //取relationModel
        SerialNumRelationModel serialNumRelationModel = (SerialNumRelationModel) map.get("serialNumRelationModel");
        //判断num是否符合规范,即长度是否大于序列长度
        if (serialNumRelationModel.getSeqMaxlength() >= String.valueOf(num).length()) {
            String code = formatCodeNum(serialNumInfoModel, serialNumRelationModel, num);
            //返回code
            return ResponseMessage.ok(code);
        } else {
            return ResponseMessage.error("下一个自增序号大于序号最大长度,不可再取.请扩大自增序号长度");
        }
    }

    //下一个编号的函数调用方法,和mapper.xml层联系
    private int getNextNum(String seqName) {
        int nextNum = serivalNumMapper.getNextNum(seqName);
        return nextNum;
    }

    /**
     * 编号回退
     *
     * @param relationObj 关联对象
     * @param serialCode  SerialNumInfo唯一标识code
     * @param step        回退步长
     */
    @Override
    public ResponseMessage fallbackNum(String relationObj, String serialCode, int step) {
        Map<String, Object> map = getSerialInfo(relationObj, serialCode);
        //3.根据第2步骤SerialNumRelationModel.sequenceName 执行函数nextval(map.get("serialNumRelationModel").getSequence())
        SerialNumRelationModel relationModel = (SerialNumRelationModel) map.get("serialNumRelationModel");
        // 获取当前sequence值
        int currentNum = serivalNumMapper.getCurrvalNum(relationModel.getSequenceName());
        // 判断回退是否小于起始值
        if (relationModel.getStartNum() > (currentNum - step)) {
            return ResponseMessage.error("回退失败,回退后小于起始值" + relationModel.getStartNum() + ",请检查确认");
        } else {
            //函数取序号
            int num = getFallbackNum(((SerialNumRelationModel) map.get("serialNumRelationModel")).getSequenceName(), currentNum - step);
            if (num > 0) {
                return ResponseMessage.ok("回退成功");
            }
            return ResponseMessage.error("回退失败,回退后小于起始值" + relationModel.getStartNum() + ",请检查确认");
        }
    }

    //编号回退的函数调用方法,和mapper.xml层联系
    private int getFallbackNum(String seqName, Integer setVal) {
        int fallbackNum = serivalNumMapper.getFallbackNum(seqName, setVal);
        return fallbackNum;
    }

    /**
     * 归零
     *
     * @return
     */
    @Override
    public ResponseMessage retToZero(SerialNumRelationDTO serialNumRelationDTO) {
        //初始化
        List<SerialNumRelationModel> modelList = null;
        //获取归零周期
        try {
            modelList = relationService.list(new QueryWrapper<SerialNumRelationModel>()
                    .lambda()
                    .eq(SerialNumRelationModel::getZeroCycle, serialNumRelationDTO.getZeroCycle()));
        } catch (Exception e) {
            return ResponseMessage.error("归零失败");
        }
        //更新序号
        try {
            for (SerialNumRelationModel relationModel : modelList) {
                sequenceService.update(new UpdateWrapper<SequenceModel>()
                        .lambda()
                        .eq(SequenceModel::getName, relationModel.getSequenceName())
                        .set(SequenceModel::getCurrentValue, relationModel.getStartNum()));
                return ResponseMessage.ok("归零成功");
            }
        } catch (Exception e) {
            return ResponseMessage.error("归零失败");
        }
        return ResponseMessage.error("归零失败");
    }
}

这里有三个接口用到了数据库函数来写的,就是sequence表,相关接口就是当前***和下一个***,还有回滚序号三个接口,这三个要好好学习.

相关标签: 学习中