St. Regis takeaway Day5, a takeaway project based on Springboot and mybatis

St. Regis Takeaway Day5

New package

​ Insert the package information entered on the new page into the setmeal table, and insert the package and dish related data into the setmeal_dish table at the same time.

The new package involves two tables:

  1. setmeal set menu
  2. setmeal_dish set meal dish relationship table

First, the basic structure of classes and interfaces

  1. Entity class SetmealDish
  2. DTO SetmealDto
  3. Mapper interface SetmealDishMapper
  4. Business layer interface SetmealDishService
  5. Business layer implementation class SetmealDishServicelmpl
  6. Control layer SetmealController

2. Front-end page interaction process

  1. The page (backend/page/combo/add.html) sends an ajax request, requesting the server to obtain package classification data and display it in the drop-down box
  2. The page sends an ajax request to request the server to obtain the dish classification data and display it in the add dish window
  3. The page sends an ajax request to request the server to query the corresponding dish data according to the dish classification and display it in the add dish window
  4. The page sends a request for image upload, and requests the server to save the image to the server
  5. The page sends a request to download the image, and echoes the uploaded image
  6. Click the save button, send an ajax request, and submit the package-related data to the server in the form of json

3. Code implementation

1. Entity class SetmealDish
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.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 套餐菜品关系
 */
@Data
public class SetmealDish implements Serializable {
    
    

    private static final long serialVersionUID = 1L;

    private Long id;


    //套餐id
    private Long setmealId;


    //菜品id
    private Long dishId;


    //菜品名称 (冗余字段)
    private String name;

    //菜品原价
    private BigDecimal price;

    //份数
    private Integer copies;


    //排序
    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;


    //是否删除
    private Integer isDeleted;
}

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

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

@Mapper
public interface SetmealDishMapper extends BaseMapper<SetmealDish> {
    
    

3. Business layer interface SetmealDishService
package com.study.service;

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

public interface SetmealDishService extends IService<SetmealDish> {
    
    
}

4. Business layer implementation class SetmealDishServicelmpl
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. Control layer SetmealController
package com.study.controller;

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

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    
    

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
    
    
        log.info("套餐信息:{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }
}

Paging query

1. Front-end and server-side interaction process

  1. The page (backend/page/combo/list.html) sends an ajax request, submits the paging query parameters (page, pageSize, name) to the server, and obtains the paging data page sending request
  2. Request the server to download pictures for page picture display and develop package information pagination query function

2. Code implementation

Add the following code to the SetmealController class

 /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
    
    
        Page<Setmeal> pageInfo=new Page<>();
        Page<SetmealDto> dtoPage=new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records=pageInfo.getRecords();
        List<SetmealDto> list=records.stream().map((item)->{
    
    
            SetmealDto setmealDto=new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();
            Category category=categoryService.getById(categoryId);
            if(category!=null){
    
    
                String categoryName=category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

delete function

1. Front-end and back-end interaction process

1. When deleting a single package, the page sends an ajax request to delete the corresponding package according to the package id.
Request URL: http://localhost:8080/setmeal?ids=1414118011303899137

Request Method: DELETE

2. When deleting multiple packages, the page sends an ajax request to delete the corresponding package according to the submitted multiple package ids.
Request URL: http://localhost:8080/setmeal?ids=1414131634248101890,1414118011303899137
Request Method: DELETE

2. Code development

Add the following code to the SetmealController class

/**
     * 套餐删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
    
    
        log.info("ids:{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐删除成功");
    }

Improve other functions

1. Query function

 @GetMapping("list")
    public R<List<Setmeal>> list(Setmeal setmeal){
    
    
        log.info("setmeal:{}",setmeal);
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(setmeal.getName()),Setmeal::getName,setmeal.getName());
        queryWrapper.eq(null!=setmeal.getCategoryId(),Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(null!=setmeal.getStatus(),Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        return R.success(setmealService.list(queryWrapper));
    }

2. Modify package status function

@PostMapping("/status/{st}")
    public R<String> setStatus(@PathVariable int st, String ids){
    
    
        //处理string 转成Long
        String[] split = ids.split(",");
        List<Long> idList = Arrays.stream(split).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

        //将每个id new出来一个Dish对象,并设置状态
        List<Setmeal> setmeals = idList.stream().map((item) -> {
    
    
            Setmeal dish = new Setmeal();
            dish.setId(item);
            dish.setStatus(st);
            return dish;
        }).collect(Collectors.toList()); //Dish集合

        log.info("status ids : {}",ids);
        setmealService.updateBatchById(setmeals);//批量操作
        return R.success("操作成功");
    }

Alibaba Cloud Platform

1. Platform steps

Log in to Alibaba Cloud –> SMS Service –> Free Open –> Accesskey Management Setting Key –> Apply for Signature and Template

二、JavaAPI

package com.study.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 短信发送工具类
 */
public class SMSUtils {
    
    

	/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 */
	public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
    
    
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tQVLLFZqKHYFZ9qxpvk",
				"bpZLPBlvZ4ZOpgoC5Ru6pRVBTZgd7S");
		IAcsClient client = new DefaultAcsClient(profile);

		SendSmsRequest request = new SendSmsRequest();
		request.setSysRegionId("cn-hangzhou");
		request.setPhoneNumbers(phoneNumbers);
		request.setSignName(signName);
		request.setTemplateCode(templateCode);
		request.setVersion("2017-05-25");
		request.setTemplateParam("{\"code\":\""+param+"\"}");
		try {
    
    
			SendSmsResponse response = client.getAcsResponse(request);
			System.out.println("短信发送成功");
		}catch (ClientException e) {
    
    
			e.printStackTrace();
		}
	}

}

package com.study.utils;

import java.util.Random;

/**
 * 随机生成验证码工具类
 */
public class ValidateCodeUtils {
    
    
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
    
    
        Integer code =null;
        if(length == 4){
    
    
            code = new Random().nextInt(9999);//生成随机数,最大为9999
            if(code < 1000){
    
    
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
    
    
            code = new Random().nextInt(999999);//生成随机数,最大为999999
            if(code < 100000){
    
    
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
    
    
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return
     */
    public static String generateValidateCode4String(int length){
    
    
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capstr = hash1.substring(0, length);
        return capstr;
    }
}

Guess you like

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