0


后端学习1.2:实现增加用户工作计划功能

功能要求

增加一张新表单,实现增加用户工作计划功能。

约定字段:
{
    "id": "唯一标识",
    "uuid": "请使用java.util.UUID生成uuid",
    "userId": "用户id",
    "taskTime": "工作计划开始时间",
    "detail": "具体工作计划内容",
    "createTime": "增加时间",
    "updateTime": "修改时间"
}

1. 实现基本的增删改查接口;
2. 使用poi,实现通过excel表单导入工作计划,以及导出工作计划的excel表单;
3. 使用spring框架自带的定时任务功能,频率为1分钟1次,对尚未提醒过而到达计划开始时间的工作计划在日志中打出信息。

开发工具:IDEA
技术:Springboot+mybatis+mybatisplus+mysql+postman

1、创建新表

CREATETABLE`userworkplan`(`id`intNOTNULLAUTO_INCREMENTCOMMENT'唯一标识',`uuid`varchar(255)CHARACTERSET utf8 COLLATE utf8_general_ci NOTNULLCOMMENT'java.util.UUID生成',`userId`varchar(255)CHARACTERSET utf8 COLLATE utf8_general_ci NOTNULLCOMMENT'用户标识',`taskTime`datetimeNOTNULLCOMMENT'工作计划开始时间',`detail`varchar(255)CHARACTERSET utf8 COLLATE utf8_general_ci DEFAULTNULLCOMMENT'具体工作计划内容',`createTime`datetimeDEFAULTNULLCOMMENT'增加时间',`updateTime`datetimeDEFAULTNULLCOMMENT'修改时间',`alarmCode`intunsignedDEFAULT'0'COMMENT'0表示未提醒,1表示已提醒',PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBAUTO_INCREMENT=23DEFAULTCHARSET=utf8mb3;

2、完成增删改查

下面仅展示对应的xml文件:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.mapper.UserWorkPlanMapper"><resultMapid="BaseResultMap"type="com.example.demo.entity.UserWorkPlan"><resultcolumn="id"jdbcType="INTEGER"property="id"/><resultcolumn="uuid"jdbcType="VARCHAR"property="uuid"/><resultcolumn="userId"jdbcType="VARCHAR"property="userId"/><resultcolumn="taskTime"property="taskTime"/><resultcolumn="detail"jdbcType="VARCHAR"property="detail"/><resultcolumn="createTime"property="createTime"/><resultcolumn="updateTime"property="updateTime"/><resultcolumn="alarmCode"jdbcType="INTEGER"property="alarmCode"/></resultMap><insertid="addUserWorkPlan"parameterType="com.example.demo.entity.UserWorkPlan">
        INSERT INTO `userworkplan` (`uuid`,`userId`,`taskTime`,`detail`,`createTime`,`updateTime`) VALUES (#{uuid},#{userId},#{taskTime},#{detail},#{createTime},#{updateTime})
    </insert><deleteid="deleteUserWorkPlan">
        DELETE FROM `userworkplan` WHERE id=#{id}
    </delete><updateid="updateUserWorkPlan"parameterType="com.example.demo.entity.UserWorkPlan">
        UPDATE `userworkplan`
        <trimprefix="SET"suffixOverrides=","><iftest="null != userWorkPlan.userId and '' != userWorkPlan.userId">
            userId=#{userWorkPlan.userId},
        </if><iftest="null != userWorkPlan.taskTime">
            taskTime=#{userWorkPlan.taskTime},
        </if><iftest="null != userWorkPlan.detail and '' != userWorkPlan.detail">
            detail=#{userWorkPlan.detail},
        </if><iftest="null != userWorkPlan.createTime">
            createTime=#{userWorkPlan.createTime},
        </if><iftest="null != userWorkPlan.updateTime">
            updateTime=#{userWorkPlan.updateTime},
        </if><iftest="1 == userWorkPlan.alarmCode">
            alarmCode=#{userWorkPlan.alarmCode},
        </if></trim>
        where id=#{userWorkPlan.id}
    </update><selectid="getUserWorkPlanInfo"resultMap="BaseResultMap">
        SELECT id,uuid,userId,taskTime,detail,createTime,updateTime FROM `userworkplan` WHERE id=#{id}
    </select><selectid="getUserWorkPlanList"resultMap="BaseResultMap">
        SELECT * FROM `userworkplan`
        <where><iftest="id != 0">
                and id = #{id}
            </if><iftest="userId != null and userId != ''">
                and userId = #{userId}
            </if><iftest="uuid != null and uuid != ''">
                and uuid = #{uuid}
            </if><iftest="taskTime != null">
                and taskTime = #{taskTime}
            </if><iftest="detail != null and detail!= ''">
                and detail like concat('%',#{detail},'%')
            </if><iftest="createTime != null">
                and createTime = #{createTime}
            </if><iftest="updateTime != null">
                and updateTime = #{updateTime}
            </if></where></select><selectid="getUserWorkPlanListAll"resultMap="BaseResultMap">
        SELECT * FROM `userworkplan` WHERE alarmCode=#{alarmCode} and taskTime=#{taskTime}
    </select><insertid="insertForEach"parameterType="java.util.List">
        INSERT INTO `userworkplan` (`uuid`,`userId`,`taskTime`,`detail`,`createTime`,`updateTime`,`alarmCode`) values
        <foreachcollection="list"item="item"index="index"separator=",">
            (
             #{item.uuid},
             #{item.userId},
             #{item.taskTime},
             #{item.detail},
             #{item.createTime},
             #{item.updateTime},
             #{item.alarmCode}
            )
        </foreach></insert></mapper>

3、使用poi,实现通过excel表单导入、导出工作计划

3.1 添加依赖:

<!--S        poi依赖包--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version></dependency><!--S        poi依赖包-->

3.2 导入

3.2.1 思路

1、获取excel数据,然后把每行数据用一个对象存起来,然后添加到list中;
    1.1读取工作簿——>读取shell——>服务行Row——>读取column列——>再一个一个set到对象里
2、编写批量新增方法,传入参数list
    2.1sql语句用foreach
    2.2这里也可以,每新建一个对象,则添加一条记录,就不用编写批量新增方法,可以直接使用新增一条的方法
3、成功失败逻辑判断:成功,返回成功条数;失败,返回失败信息;

3.2.2 主要代码如下:

3.2.2.1 utils包下定义ImportExcelUtils类

packagecom.example.demo.utils;importcom.example.demo.entity.UserWorkPlan;importorg.apache.poi.ss.usermodel.CellType;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importorg.springframework.web.multipart.MultipartFile;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.List;importjava.util.UUID;/**
 * @Date 2022/7/29 11:12
 * @Description 导入Excel
 */publicclassImportExcelUtils{//获取excel的数据,然后把每行的数据用一个对象存起来,然后都添加到list中publicList<UserWorkPlan>importExcel(MultipartFile file)throwsIOException{List<UserWorkPlan> userWorkPlans=newArrayList<>();SimpleDateFormat df=newSimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式System.out.println(file.getOriginalFilename());String filepath="这边填写本地导入路径/"+file.getOriginalFilename();try{// 1.创建workbook对象,读取整个文档XSSFWorkbook wb =newXSSFWorkbook(filepath);// 2.读取页脚sheetXSSFSheet sheetAt = wb.getSheetAt(0);// 3.循环读取某一行int index =0;for(Row row : sheetAt){// 4.读取每一行的单元格if(index ==0){
                    index++;continue;}//创建一个用户工作计划对象UserWorkPlan userWorkPlan =newUserWorkPlan();//将Excel表中单元格的值与用户工作计划对象的值对应if(row.getCell(2).getStringCellValue()==""){String uuid=String.valueOf(UUID.randomUUID());
                    userWorkPlan.setUuid(uuid);}else{
                    userWorkPlan.setUuid(row.getCell(1).getStringCellValue());}//因为userId是数字,Excel默认是数字类型,数据库是字符串类型,所以需要设置下类型
                row.getCell(2).setCellType(CellType.STRING);
                userWorkPlan.setUserId(row.getCell(2).getStringCellValue());
                userWorkPlan.setTaskTime(df.parse(row.getCell(3).getStringCellValue()));
                userWorkPlan.setDetail(row.getCell(4).getStringCellValue());if(row.getCell(5).getStringCellValue()==""){
                    userWorkPlan.setCreateTime(null);}else{
                    userWorkPlan.setCreateTime(df.parse(row.getCell(5).getStringCellValue()));}if(row.getCell(6).getStringCellValue()==""){
                    userWorkPlan.setUpdateTime(null);}else{
                    userWorkPlan.setUpdateTime(df.parse(row.getCell(6).getStringCellValue()));}if(row.getCell(7)==null){
                    userWorkPlan.setAlarmCode(0);}else{
                    userWorkPlan.setAlarmCode((int) row.getCell(7).getNumericCellValue());}
                userWorkPlans.add(userWorkPlan);}catch(Exception e){
            e.printStackTrace();}return userWorkPlans;}}

3.2.2.2 service包下impl包下的具体功能实现:

@OverridepublicintimportUserWorkPlanExcel(MultipartFile file)throwsServiceException{ImportExcelUtils importExcelUtils=newImportExcelUtils();try{List<UserWorkPlan> userWorkPlans=importExcelUtils.importExcel(file);//链接数据库编写批量新增的方法,传入listint count=userWorkPlanMapper.insertForEach(userWorkPlans);//成功失败逻辑判断,成功返回成功条数,失败返回失败信息if(count==userWorkPlans.size()){return count;}else{thrownewServiceException(500,"导入失败!");}}catch(IOException e){
            e.printStackTrace();thrownewServiceException(500,"导入失败!");}}

3.2.2.3 controller里:

//导入工作计划@PostMapping(value="/importExcel")@ResponseBodypublicintimportExcel(@RequestParam("file")MultipartFile file)throwsServiceException{return service.importUserWorkPlanExcel(file);}

3.2.3 postman测试:

headers里选择content-type,值为multipart/form-data;
body选中form-data;key值选择file,右边便会出现上传文件按钮,即可进行测试;

在这里插入图片描述

在这里插入图片描述

3.3 导出

3.3.1 思路

1、链接数据库,编写获取数据库对应表全部数据的方法;
2、创建一个Excel模板——>创建sheet,定义sheet表名——>创建第一行标题——>从第二行开始,利用for循环,进入到每一行,针对每一列进行数据赋值
3、利用文件输出流导出Excel文件

3.3.2 主要代码如下:

3.3.2.1 utils包下定义ExportExcelUtils类

packagecom.example.demo.utils;importcom.example.demo.entity.UserWorkPlan;importorg.apache.poi.ss.usermodel.*;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importjava.io.File;importjava.io.FileOutputStream;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.List;/**
 * @Date 2022/7/29 9:28
 * @Description 导出Excel
 */publicclassExportExcelUtils{publicintexportExcel(List<UserWorkPlan> userWorkPlans){//创建一个Excel模板Workbook workbook =newXSSFWorkbook();//获取sheet的名字  以表名来命名String sheetName ="用户工作计划表";//创建sheetSheet sheet = workbook.createSheet(sheetName);//创建第一行Row header = sheet.createRow(0);//从第二行开始 --来控制插入的行数int rowSize =1;//控制第一行的列//定义表格第一行String[] titles ={"id","uuid","userId","taskTime","detail","createTime","updateTime","alarmCode"};for(int i =0; i < titles.length; i++){//取到每一行的值由i控制Cell cell = header.createCell(i);
            cell.setCellValue(titles[i]);//设置列的宽度
            sheet.setColumnWidth(i,100*50);}SimpleDateFormat df=newSimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式//遍历数据集合for(int j =0; j < userWorkPlans.size(); j++){//for循环是从0开始的,但是0行在第一个for循环已经设置好了Row rowDate=sheet.createRow(j+1);//找到每一行的下标UserWorkPlan userWorkPlan=userWorkPlans.get(j);//从第0行第一列开始赋值Cell cell=rowDate.createCell(0);
            cell.setCellValue(userWorkPlan.getId());//第二列Cell cell2=rowDate.createCell(1);
            cell2.setCellValue(userWorkPlan.getUuid());//第三列Cell cell3=rowDate.createCell(2);
            cell3.setCellValue(userWorkPlan.getUserId());//第四列Cell cell4=rowDate.createCell(3);
            cell4.setCellValue(df.format(userWorkPlan.getTaskTime()));//第五列Cell cell5=rowDate.createCell(4);
            cell5.setCellValue(userWorkPlan.getDetail());//第六列Cell cell6=rowDate.createCell(5);
            cell6.setCellValue(df.format(userWorkPlan.getCreateTime()));//第七列Cell cell7=rowDate.createCell(6);if(userWorkPlan.getUpdateTime()==null){
                cell7.setCellValue("");}else{
                cell7.setCellValue(df.format(userWorkPlan.getUpdateTime()));}//第八列Cell cell8=rowDate.createCell(7);
            cell8.setCellValue(userWorkPlan.getAlarmCode());}//输出数据System.out.println(userWorkPlans);//定义文件导出路径File file =newFile("文件导出路径/表名.xlsx");if(file.exists()){
            file.delete();//存在就删除}//保存到本地try{//输出流FileOutputStream fileoutputstream=newFileOutputStream(file);//写出
            workbook.write(fileoutputstream);//关闭
            workbook.close();System.out.println("导出成功!!");return1;}catch(Exception e){//抛出异常
            e.printStackTrace();return0;}}}

3.3.2.1 service包下impl包下的具体功能实现:

@OverridepublicintexportUserWorkPlanExcel()throwsServiceException{//获取数据库中数据List<UserWorkPlan> userWorkPlans = userWorkPlanMapper.getUserWorkPlanList(0,null,null,null,null,null,null);ExportExcelUtils exportExcelUtils=newExportExcelUtils();int count= exportExcelUtils.exportExcel(userWorkPlans);if(count>0){return1;}else{thrownewServiceException(500,"导出失败!");}}

3.3.2.3 controller里:

//导出工作计划表@GetMapping(value="/exportExcel")publicintexportExcel()throwsServiceException{return service.exportUserWorkPlanExcel();}

4、定时

通过两个注解:@EnableScheduling和@Schedule(cron=……)

1、启动类:

packagecom.example.demo;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableScheduling//开启定时执行功能,异步调用publicclassDemoApplication{publicstaticvoidmain(String[] args){SpringApplication.run(DemoApplication.class, args);}}

2、具体要定时的提醒的方法:

/**
     * 每60秒执行一次
     */@Scheduled(cron ="*/60 * * * * ?")publicvoidsetAlarm(){//不能有参数SimpleDateFormat df=newSimpleDateFormat("yyyy-MM-dd HH:mm");String datestr=df.format(newDate());// format  为格式化方法Date date =null;try{
            date = df.parse(datestr);}catch(ParseException e){
            e.printStackTrace();}List<UserWorkPlan> userWorkPlans=userWorkPlanMapper.getUserWorkPlanListAll(date,0);//获取所有未提醒的if(userWorkPlans.size()>0){for(int i=0;i<userWorkPlans.size();i++){UserWorkPlan currentTask=userWorkPlans.get(i);//当前任务判断System.err.println(LocalDateTime.now());System.out.println("到时间啦!你该"+currentTask.getDetail()+"啦!");
                currentTask.setAlarmCode(1);
                userWorkPlanMapper.updateUserWorkPlan(currentTask);//完善:提醒之后,将提醒状态更新为 已提醒 数据库中该字段值改为1}}}

5、学习到的知识点

  1. 利用poi实现简单的Excel导入导出功能
  2. spring框架自带的定时任务功能
  3. 校验除了在controller层写之外,也可在service接口的实现类serviceImpl里
  4. postman上传文件的测试方法
  5. string转date用parse;date转string用format
SimpleDateFormat df=newSimpleDateFormat("yyyy-MM-dd HH:mm");String datestr=df.format(newDate());// format  为格式化方法Date strdate=df.parse("2022-07-29 17:00:00");
标签: java spring boot 后端

本文转载自: https://blog.csdn.net/qq_45722699/article/details/126028319
版权归原作者 Congee_porridge 所有, 如有侵权,请联系我们删除。

“后端学习1.2:实现增加用户工作计划功能”的评论:

还没有评论