查询收藏(头歌)

第1关:查询收藏

任务描述

本关任务:实现查询用户收藏的商品功能。

相关知识

为了完成本关任务,你需要掌握:

  1. 查询用户收藏的商品;
  2. 功能实现。
查询用户收藏的商品

如下图是收藏页面的展示:

一般是前端页面通过 ajax 请求服务器,服务器查询数据库后得到 json 数据通过 js 渲染在网页上。

功能实现
  1. dao 层: CollectDao:查询用户收藏。
     
      
    1. //根据用户 id 查询用户的收藏
    2. @Select("select * from collect where user_id=#{user_id}")
    3. List<Collect> getCollect(int user_id);
    ProductDao:查询商品信息。
     
      
    1. //根据商品 id 查询商品信息
    2. @Select("select * from product where product_id=#{product_id}")
    3. Product getProductByID(int product_id);
  2. service 层定义接口: CollectService:
     
      
    1. //定义查询收藏的 service 接口
    2. List<Collect> getCollect(int user_id);
    ProductService:
     
      
    1. //定义根据 Id 查询商品信息的 service 接口
    2. Product getProductByID(int product_id);
  3. service 层 impl 类: CollectServiceImpl :
     
      
    1. @Override
    2. public List<Collect> getCollect(int user_id) {
    3. //调用 dao 层方法,查询用户的收藏
    4. return collectDao.getCollect(user_id);
    5. }
    ProductServiceImpl:
     
      
    1. @Override
    2. public Product getProductByID(int product_id) {
    3. //从 redis 中取商品集合 map
    4. Map<Object, Object> productMap = redisTemplate.opsForHash().entries("product");
    5. if(productMap.isEmpty()){
    6. //redis 无 map,从 dao 层查询商品信息存入 map ,map 存入 redis
    7. Product product = productDao.getProductByID(product_id);
    8. productMap.put(product_id+"",product);
    9. redisTemplate.opsForHash().putAll("product",productMap);
    10. }else if(productMap.get(product_id)==null){
    11. //redis无该商品,从 dao 层查询商品信息存入 map ,map 存入 redis
    12. productMap.put(product_id+"",productDao.getProductByID(product_id));
    13. redisTemplate.opsForHash().putAll("product",productMap);
    14. }
    15. //返回 map 集合
    16. return (Product) productMap.get(product_id+"");
    17. }
  4. controller 层:接收参数,判断用户是否有收藏商品,如果有就返回商品信息。
     
      
    1. @RestController
    2. @RequestMapping(value = "/collect")
    3. public class CollectController {
    4. @Autowired
    5. private CollectService collectService;
    6. @Autowired
    7. private ProductService productService;
    8. /**
    9. * 查询收藏
    10. * @param paramMap
    11. * @return
    12. */
    13. @RequestMapping(value = "/getCollect")
    14. public Map getCollect(@RequestBody Map<String,Integer> paramMap){
    15. //接收参数
    16. Integer user_id = paramMap.get("user_id");
    17. HashMap<String, Object> map = new HashMap<>();
    18. //参数的非空判断
    19. if(user_id==null){
    20. map.put("code","004");
    21. map.put("msg","用户未登录");
    22. }else{
    23. //调用 service 层方法,查询用户的收藏,用户没有收藏返回 "code","002" "msg","该用户没有收藏的商品"
    24. List<Collect> collectList = collectService.getCollect(user_id);
    25. if(collectList==null){
    26. map.put("code","002");
    27. map.put("msg","该用户没有收藏的商品");
    28. }else{
    29. //否则就循环根据收藏的商品 id 查询商品的具体信息
    30. for(Collect collect:collectList){
    31. Product product = productService.getProductByID(collect.getProduct_id());
    32. collect.setProduct_name(product.getProduct_name());
    33. collect.setProduct_picture(product.getProduct_picture());
    34. collect.setProduct_price(product.getProduct_price());
    35. collect.setProduct_selling_price(product.getProduct_selling_price());
    36. collect.setProduct_title(product.getProduct_title());
    37. }
    38. //返回 map 结果集 "code","001" "collectList",collectList
    39. map.put("collectList",collectList);
    40. map.put("code","001");
    41. }
    42. }
    43. return map;
    44. }
  5. 数据库如下:、 商品表:
    字段名称类型备注
    product_idint(11)NOT NULL AUTO_INCREMENT'商品id'
    product_namechar(100)NOT NULL'商品名'
    category_idint(11)NOT NULL'类型id'
    product_titlechar(30)NOT NULL'商品标题'
    product_introtextNOT NULL'商品描述'
    product_picturechar(200)DEFAULT NULL'商品图片'
    product_pricedecimal(10,2)NOT NULL'商品价格'
    product_selling_pricedecimal(10,2)NOT NULL'商品售价'
    product_numint(11)NOT NULL'商品存量'
    product_salesint(11)NOT NULL'商品销售数量'
    statusint(11)DEFAULT NULL'商品状态'
    收藏表:
    字段名称类型备注
    idint(11)NOT NULL AUTO_INCREMENT'收藏表主键id'
    user_idint(11)NOT NULL'用户id'
    product_idint(11)NOT NULL'商品id'
    collect_timedatetimeNOT NULL'收藏时间'

编程要求

在右侧 CollectDao.java、ProductDao.java、CollectService.java、ProductService.java、CollectServiceImpl.ava、ProductServiceImpl.java、CollectController.java 文件里 Begin-End 处根据提示补充代码。

测试说明

平台会对你编写的代码进行测试:发送请求检验结果集是否正确。

测试输入:

 
  1. {
  2. "user_id":"1018"
  3. }

预期输出:

 
  1. {"code":"001","collectList":[{"id":1,"user_id":1018,"product_id":1,"collect_time":"2022-05-25 14:08:29","product_picture":"public/imgs/phone/Redmi-k30.png","product_name":"Redmi K30","product_title":"120Hz流速屏,全速热爱","product_selling_price":1499.00,"product_price":2000.00},{"id":2,"user_id":1018,"product_id":2,"collect_time":"2022-05-25 14:08:39","product_picture":"public/imgs/phone/Redmi-k30-5G.png","product_name":"Redmi K30 5G","product_title":"双模5G,120Hz流速屏","product_selling_price":2599.00,"product_price":2599.00},{"id":3,"user_id":1018,"product_id":3,"collect_time":"2022-05-25 14:08:49","product_picture":"public/imgs/phone/Mi-CC9.png","product_name":"小米CC9 Pro","product_title":"1亿像素,五摄四闪","product_selling_price":2599.00,"product_price":2799.00}]}

开始你的任务吧,祝你成功!

CollectDao.java
package com.www.dao;

import com.www.entity.Collect;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface CollectDao {

    //根据用户 id 查询用户的收藏
    /**********************Begin**********************/
     @Select("select * from collect where user_id=#{user_id}")  
 List<Collect> getCollect(int user_id);
    /**********************End**********************/
}
ProductDao.java
package com.www.dao;


import com.www.entity.Product;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;


@Repository
public interface ProductDao {

    //根据商品信息查询商品信息
    /**********************Begin**********************/
     @Select("select * from product where product_id=#{product_id}")  
 Product getProductByID(int product_id);  
    /**********************End**********************/
}
CollectService.java
package com.www.service;

import com.www.entity.Collect;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public interface CollectService {
    //定义查询收藏的 service 接口
    /**********************Begin**********************/
     List<Collect> getCollect(int user_id); 
    /**********************End**********************/

}
ProductService.java
package com.www.service;

import com.www.entity.Product;
import org.springframework.stereotype.Component;



@Component
public interface ProductService {
    //定义根据 Id 查询商品信息的 service 接口
    /**********************Begin**********************/
   Product getProductByID(int product_id); 
    /**********************End**********************/

}
CollectServiceImpl.java
package com.www.service.impl;

import com.www.dao.CollectDao;
import com.www.entity.Collect;
import com.www.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("collectService")
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectDao collectDao;


    @Override
    public List<Collect> getCollect(int user_id) {
        //调用 dao 层方法,查询用户的收藏
        /**********************Begin**********************/
        return collectDao.getCollect(user_id);  
        /**********************End**********************/
    }

}
ProductServiceImpl.java
package com.www.service.impl;

import com.www.dao.ProductDao;
import com.www.entity.Category;
import com.www.entity.Product;
import com.www.entity.Product_picture;
import com.www.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;



    @Override
    public Product getProductByID(int product_id) {
        /**********************Begin**********************/
        //从 redis 中取商品集合 map
        Map<Object, Object> productMap = redisTemplate.opsForHash().entries("product");
        if(productMap.isEmpty()){     
         //redis 无 map,从 dao 层查询商品信息存入 map ,map 存入 redis  
         Product product = productDao.getProductByID(product_id);  
         productMap.put(product_id+"",product);  
         redisTemplate.opsForHash().putAll("product",productMap);  
     }else if(productMap.get(product_id)==null){     
         //redis无该商品,从 dao 层查询商品信息存入 map ,map 存入 redis  
         productMap.put(product_id+"",productDao.getProductByID(product_id));  
         redisTemplate.opsForHash().putAll("product",productMap);  
     }  
     //返回 map 集合  
     return (Product) productMap.get(product_id+"");  
        
        /**********************End**********************/
    }

}
CollectController.java
package com.www.controller;

import com.www.entity.Collect;
import com.www.entity.Product;
import com.www.service.CollectService;
import com.www.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/collect")
public class CollectController {

    @Autowired
    private CollectService collectService;
    
    @Autowired
    private ProductService productService;

    /**
     * 查询收藏
     * @param paramMap
     * @return
     */
    @RequestMapping(value = "/getCollect")
    public Map getCollect(@RequestBody Map<String,Integer> paramMap){
        /**********************Begin**********************/
        //接收参数  
     Integer user_id = paramMap.get("user_id");  
     HashMap<String, Object> map = new HashMap<>();  
     //参数的非空判断  
     if(user_id==null){  
         map.put("code","004");  
         map.put("msg","用户未登录");  
     }else{  
     //调用 service 层方法,查询用户的收藏,用户没有收藏返回 "code","002" "msg","该用户没有收藏的商品"  
         List<Collect> collectList = collectService.getCollect(user_id);  
         if(collectList==null){  
             map.put("code","002");  
             map.put("msg","该用户没有收藏的商品");  
         }else{  
     //否则就循环根据收藏的商品 id 查询商品的具体信息   
             for(Collect collect:collectList){  
                 Product product = productService.getProductByID(collect.getProduct_id());  
                 collect.setProduct_name(product.getProduct_name());  
                 collect.setProduct_picture(product.getProduct_picture());  
                 collect.setProduct_price(product.getProduct_price());  
                 collect.setProduct_selling_price(product.getProduct_selling_price());  
                 collect.setProduct_title(product.getProduct_title());  
             }  
     //返回 map 结果集 "code","001" "collectList",collectList  
             map.put("collectList",collectList);  
             map.put("code","001");  
         }  
     }  
     return map;  
        /**********************End**********************/
    }
}
Collect.java
package com.www.entity;

import lombok.Data;

import java.io.Serializable;
import java.math.BigDecimal;


@Data
public class Collect implements Serializable {

    private int id;
    private int user_id;
    private int product_id;
    private String collect_time;
    private String product_picture;
    private String product_name;
    private String product_title;
    private BigDecimal product_selling_price;
    private BigDecimal product_price;

}
Product.java
package com.www.entity;

import lombok.Data;

import java.io.Serializable;
import java.math.BigDecimal;


@Data
public class Product implements Serializable {

    private int product_id;
    private String product_name;
    private int category_id;
    private String product_title;
    private String product_intro;
    private String product_picture;
    private BigDecimal product_price;   //原价
    private BigDecimal product_selling_price;    //售价
    private int product_num;
    private int product_sales;
    private int status;
}

加油哦,同学们!

### 面向对象设计原则概述 面向对象设计(Object-Oriented Design, OOD)是一种基于面向对象编程理念的设计方法,旨在创建灵活、可重用且易于维护的软件系统[^1]。核心概念包括类、对象、继承、封装和多态性。 #### SOLID原则简介 SOLID 是五个重要的面向对象设计原则的首字母缩写词,有助于开发人员编写更高质量的代码: - **单一职责原则 (Single Responsibility Principle)** 每个类应该只有一个引起它变化的原因。这意味着每个类应仅负责一项功能或行为[^2]。 - **开闭原则 (Open/Closed Principle)** 软件实体应当对扩展开放,对修改闭。即可以通过增加新代码实现新的功能而不改变现有代码。 - **里氏替换原则 (Liskov Substitution Principle)** 子类型必须能够替换其基类型而不会影响程序的正确执行。这确保了子类可以无缝替代父类被调用的地方。 - **接口隔离原则 (Interface Segregation Principle)** 客户端不应该依赖它们不需要的方法;多个特定客户端接口优于一个通用的大接口。 - **依赖倒置原则 (Dependency Inversion Principle)** 抽象不应依赖于细节,而是相反——高层模块不应当依赖低层模块的具体实现,二者都应依赖抽象。此外,具体实现应该依赖于抽象定义。 #### 实践案例:商场收银软件 为了更好地理解和应用上述原则,考虑构建一个简单的商场收银系统作为练习项目[^3]。该系统的目的是模拟实际场景中营业员根据顾客所购商品的价格和数量来进行结算的过程。通过此过程,不仅可以加深对于面向对象的理解,还能锻炼如何运用OOD原则优化设计方案。 ```csharp // 定义商品类 public class Product { public string Name { get; set; } public double PricePerUnit { get; set; } public Product(string name, double price) { this.Name = name; this.PricePerUnit = price; } } // 订单项类表示单个商品及其数量 public class OrderItem { private readonly Product _product; public int Quantity { get; set; } public OrderItem(Product product, int quantity) { _product = product ?? throw new ArgumentNullException(nameof(product)); Quantity = Math.Max(quantity, 0); } public double GetTotalPrice() => _product.PricePerUnit * Quantity; } ``` 以上展示了部分简化版的商品管理和订单处理逻辑,在此基础上还可以继续完善其他特性如折扣计算等功能,并遵循SOLID指导方针进行合理拆分与重构。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值