编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

21.零基础开发商城项目:商品管理(后端)

wxchong 2024-09-08 10:48:02 开源技术 9 ℃ 0 评论

上一篇的18.零基础开发商城项目:商城数据库初次设计,我们把商品的表设计好了,代码生成完后,在控制器写下代码,save保存商品、list商品列表、info商品详细信息、delete删除商品。

所有代码:

package com.haiyeren.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haiyeren.entity.GoodsEntity;
import com.haiyeren.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @PostMapping("save")
    public Object save(@RequestBody GoodsEntity entity) {


        if (null != entity.getId() && entity.getId() > 0) {
            //编辑
            entity.setUpdatedAt(LocalDateTime.now());
            goodsService.updateById(entity);

        } else {
            //添加


            entity.setCreatedAt(LocalDateTime.now());
            entity.setUpdatedAt(LocalDateTime.now());
            goodsService.save(entity);

        }
        Map<String, Object> result = new HashMap<>();
        result.put("status", 1);
        return result;


    }


    @GetMapping("list")
    public Object list(Integer pageNum, Integer pageSize) {

        Map<String, Object> result = new HashMap<>();

        QueryWrapper<GoodsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        // 查询第1页,每页返回5条
        Page<GoodsEntity> page = new Page<>(pageNum, pageSize);
        IPage<GoodsEntity> iPage = goodsService.page(page, queryWrapper);
        result.put("list", iPage.getRecords());
        result.put("total", iPage.getTotal());
        result.put("status", 1);
        return result;


    }

    @GetMapping("info")
    public Object info(Long id) {
        Map<String, Object> result = new HashMap<>();

        GoodsEntity goodsEntity = goodsService.getById(id);

        result.put("status", 1);
        result.put("info", goodsEntity);
        return result;


    }

    @PostMapping("delete")
    public Object delete(Long id) {

        Map<String, Object> result = new HashMap<>();
        goodsService.removeById(id);
        result.put("status", 1);
        return result;
    }

}

这不一定是好代码,但这一定是我认为最简单的。或许代码有不足的地方,不能应付所有场景,比如用户奇奇怪怪的操作。这些后面会补充,并及时改善我们的代码

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表