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

[springboot 开发单体web shop] 7. 多种形式提供商品列表

程序员文章站 2023-11-08 18:29:46
上文回顾 "上节" 我们实现了仿 的轮播广告以及商品分类的功能,并且讲解了不同的注入方式,本节我们将继续实现我们的电商主业务,商品信息的展示。 需求分析 首先,在我们开始本节编码之前,我们先来分析一下都有哪些地方会对商品进行展示,打开 首页,鼠标下拉可以看到如下: 可以看到,在大类型下查询了部分商品 ......

上文回顾

我们实现了仿jd的轮播广告以及商品分类的功能,并且讲解了不同的注入方式,本节我们将继续实现我们的电商主业务,商品信息的展示。

需求分析

首先,在我们开始本节编码之前,我们先来分析一下都有哪些地方会对商品进行展示,打开jd首页,鼠标下拉可以看到如下:
[springboot 开发单体web shop] 7. 多种形式提供商品列表

可以看到,在大类型下查询了部分商品在首页进行展示(可以是最新的,也可以是网站推荐等等),然后点击任何一个分类,可以看到如下:
[springboot 开发单体web shop] 7. 多种形式提供商品列表

我们一般进到电商网站之后,最常用的一个功能就是搜索,搜索钢琴 结果如下:
[springboot 开发单体web shop] 7. 多种形式提供商品列表

选择任意一个商品点击,都可以进入到详情页面,这个是单个商品的信息展示。
综上,我们可以知道,要实现一个电商平台的商品展示,最基本的包含:

  • 首页推荐/最新上架商品
  • 分类查询商品
  • 关键词搜索商品
  • 商品详情展示
  • ...

接下来,我们就可以开始商品相关的业务开发了。

首页商品列表|indexproductlist

开发梳理

我们首先来实现在首页展示的推荐商品列表,来看一下都需要展示哪些信息,以及如何进行展示。

  • 商品主键(product_id)
  • 展示图片(image_url)
  • 商品名称(product_name)
  • 商品价格(product_price)
  • 分类说明(description)
  • 分类名称(category_name)
  • 分类主键(category_id)
  • 其他...

编码实现

根据一级分类查询

遵循开发顺序,自下而上,如果基础mapper解决不了,那么优先编写sql mapper,因为我们需要在同一张表中根据parent_id递归的实现数据查询,当然我们这里使用的是表链接的方式实现。因此,common mapper无法满足我们的需求,需要自定义mapper实现。

custom mapper实现

和根据一级分类查询子分类一样,在项目mscx-shop-mapper中添加一个自定义实现接口com.liferunner.custom.productcustommapper,然后在resources\mapper\custom路径下同步创建xml文件mapper/custom/productcustommapper.xml,此时,因为我们在上节中已经配置了当前文件夹可以被容器扫描到,所以我们添加的新的mapper就会在启动时被扫描加载,代码如下:

/**
 * productcustommapper for : 自定义商品mapper
 */
public interface productcustommapper {

    /***
     * 根据一级分类查询商品
     *
     * @param parammap 传递一级分类(map传递多参数)
     * @return java.util.list<com.liferunner.dto.indexproductdto>
     */
    list<indexproductdto> getindexproductdtolist(@param("parammap") map<string, integer> parammap);
}
<?xml version="1.0" encoding="utf-8"?>
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liferunner.custom.productcustommapper">
    <resultmap id="indexproductdto" type="com.liferunner.dto.indexproductdto">
        <id column="rootcategoryid" property="rootcategoryid"/>
        <result column="rootcategoryname" property="rootcategoryname"/>
        <result column="slogan" property="slogan"/>
        <result column="categoryimage" property="categoryimage"/>
        <result column="bgcolor" property="bgcolor"/>
        <collection property="productitemlist" oftype="com.liferunner.dto.indexproductitemdto">
            <id column="productid" property="productid"/>
            <result column="productname" property="productname"/>
            <result column="productmainimageurl" property="productmainimageurl"/>
            <result column="productcreatetime" property="productcreatetime"/>
        </collection>
    </resultmap>
    <select id="getindexproductdtolist" resultmap="indexproductdto" parametertype="map">
        select
        c.id as rootcategoryid,
        c.name as rootcategoryname,
        c.slogan as slogan,
        c.category_image as categoryimage,
        c.bg_color as bgcolor,
        p.id as productid,
        p.product_name as productname,
        pi.url as productmainimageurl,
        p.created_time as productcreatetime
        from category c
        left join products p
        on c.id = p.root_category_id
        left join products_img pi
        on p.id = pi.product_id
        where c.type = 1
        and p.root_category_id = #{parammap.rootcategoryid}
        and pi.is_main = 1
        limit 0,10;
    </select>
</mapper>

service实现

serviceproject 创建com.liferunner.service.iproductservice接口以及其实现类com.liferunner.service.impl.productserviceimpl,添加查询方法如下:

public interface iproductservice {

    /**
     * 根据一级分类id获取首页推荐的商品list
     *
     * @param rootcategoryid 一级分类id
     * @return 商品list
     */
    list<indexproductdto> getindexproductdtolist(integer rootcategoryid);
    ...
}

---
    
@slf4j
@service
@requiredargsconstructor(onconstructor = @__(@autowired))
public class productserviceimpl implements iproductservice {

    // requiredargsconstructor 构造器注入
    private final productcustommapper productcustommapper;

    @transactional(propagation = propagation.supports)
    @override
    public list<indexproductdto> getindexproductdtolist(integer rootcategoryid) {
        log.info("====== productserviceimpl#getindexproductdtolist(rootcategoryid) : {}=======", rootcategoryid);
        map<string, integer> map = new hashmap<>();
        map.put("rootcategoryid", rootcategoryid);
        val indexproductdtolist = this.productcustommapper.getindexproductdtolist(map);
        if (collectionutils.isempty(indexproductdtolist)) {
            log.warn("productserviceimpl#getindexproductdtolist未查询到任何商品信息");
        }
        log.info("查询结果:{}", indexproductdtolist);
        return indexproductdtolist;
    }
}

controller实现

接着,在com.liferunner.api.controller.indexcontroller中实现对外暴露的查询接口:

@restcontroller
@requestmapping("/index")
@api(value = "首页信息controller", tags = "首页信息接口api")
@slf4j
public class indexcontroller {
    ...
    @autowired
    private iproductservice productservice;

    @getmapping("/rootcategorys")
    @apioperation(value = "查询一级分类", notes = "查询一级分类")
    public jsonresponse findallrootcategorys() {
        log.info("============查询一级分类==============");
        val categoryresponsedtos = this.categoryservice.getallrootcategorys();
        if (collectionutils.isempty(categoryresponsedtos)) {
            log.info("============未查询到任何分类==============");
            return jsonresponse.ok(collections.empty_list);
        }
        log.info("============一级分类查询result:{}==============", categoryresponsedtos);
        return jsonresponse.ok(categoryresponsedtos);
    }
    ...
}

test api

编写完成之后,我们需要对我们的代码进行测试验证,还是通过使用restservice插件来实现,当然,大家也可以通过postman来测试,结果如下:
[springboot 开发单体web shop] 7. 多种形式提供商品列表

商品列表|productlist

如开文之初我们看到的京东商品列表一样,我们先分析一下在商品列表页面都需要哪些元素信息?

开发梳理

商品列表的展示按照我们之前的分析,总共分为2大类:

  • 选择商品分类之后,展示当前分类下所有商品
  • 输入搜索关键词后,展示当前搜索到相关的所有商品

在这两类中展示的商品列表数据,除了数据来源不同以外,其他元素基本都保持一致,那么我们是否可以使用统一的接口来根据参数实现隔离呢? 理论上不存在问题,完全可以通过传参判断的方式进行数据回传,但是,在我们实现一些可预见的功能需求时,一定要给自己的开发预留后路,也就是我们常说的可拓展性,基于此,我们会分开实现各自的接口,以便于后期的扩展。
接着来分析在列表页中我们需要展示的元素,首先因为需要分上述两种情况,因此我们需要在我们api设计的时候分别处理,针对于
1.分类的商品列表展示,需要传入的参数有:

  • 分类id
  • 排序(在电商列表我们常见的几种排序(销量,价格等等))
  • 分页相关(因为我们不可能把数据库中所有的商品都取出来)
    • pagenumber(当前第几页)
    • pagesize(每页显示多少条数据)

2.关键词查询商品列表,需要传入的参数有:

  • 关键词
  • 排序(在电商列表我们常见的几种排序(销量,价格等等))
  • 分页相关(因为我们不可能把数据库中所有的商品都取出来)
    • pagenumber(当前第几页)
    • pagesize(每页显示多少条数据)

需要在页面展示的信息有:

  • 商品id(用于跳转商品详情使用)
  • 商品名称
  • 商品价格
  • 商品销量
  • 商品图片
  • 商品优惠
  • ...

编码实现

根据上面我们的分析,接下来开始我们的编码:

根据商品分类查询

根据我们的分析,肯定不会在一张表中把所有数据获取全,因此我们需要进行多表联查,故我们需要在自定义mapper中实现我们的功能查询.

responsedto 实现

根据我们前面分析的前端需要展示的信息,我们来定义一个用于展示这些信息的对象com.liferunner.dto.searchproductdto,代码如下:

@data
@noargsconstructor
@allargsconstructor
@builder
public class searchproductdto {
    private string productid;
    private string productname;
    private integer sellcounts;
    private string imgurl;
    private integer pricediscount;
    //商品优惠,我们直接计算之后返回优惠后价格
}

custom mapper 实现

com.liferunner.custom.productcustommapper.java中新增一个方法接口:

    list<searchproductdto> searchproductlistbycategoryid(@param("parammap") map<string, object> parammap);

同时,在mapper/custom/productcustommapper.xml中实现我们的查询方法:

<select id="searchproductlistbycategoryid" resulttype="com.liferunner.dto.searchproductdto" parametertype="map">
        select
        p.id as productid,
        p.product_name as productname,
        p.sell_counts as sellcounts,
        pi.url as imgurl,
        tp.pricediscount
        from products p
        left join products_img pi
        on p.id = pi.product_id
        left join
        (
        select product_id, min(price_discount) as pricediscount
        from products_spec
        group by product_id
        ) tp
        on tp.product_id = p.id
        where pi.is_main = 1
        and p.category_id = #{parammap.categoryid}
        order by
        <choose>
            <when test="parammap.sortby != null and parammap.sortby == 'sell'">
                p.sell_counts desc
            </when>
            <when test="parammap.sortby != null and parammap.sortby == 'price'">
                tp.pricediscount asc
            </when>
            <otherwise>
                p.created_time desc
            </otherwise>
        </choose>
    </select>

主要来说明一下这里的<choose>模块,以及为什么不使用if标签。
在有的时候,我们并不希望所有的条件都同时生效,而只是想从多个选项中选择一个,但是在使用if标签时,只要test中的表达式为 true,就会执行if 标签中的条件。mybatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。
它的选择是按照顺序自上而下,一旦有任何一个满足条件,则选择退出。

service 实现

然后在servicecom.liferunner.service.iproductservice中添加方法接口:

    /**
     * 根据商品分类查询商品列表
     *
     * @param categoryid 分类id
     * @param sortby     排序方式
     * @param pagenumber 当前页码
     * @param pagesize   每页展示多少条数据
     * @return 通用分页结果视图
     */
    commonpagedresult searchproductlist(integer categoryid, string sortby, integer pagenumber, integer pagesize);

在实现类com.liferunner.service.impl.productserviceimpl中,实现上述方法:

    // 方法重载
    @override
    public commonpagedresult searchproductlist(integer categoryid, string sortby, integer pagenumber, integer pagesize) {
        map<string, object> parammap = new hashmap<>();
        parammap.put("categoryid", categoryid);
        parammap.put("sortby", sortby);
        // mybatis-pagehelper
        pagehelper.startpage(pagenumber, pagesize);
        val searchproductdtos = this.productcustommapper.searchproductlistbycategoryid(parammap);
        // 获取mybatis插件中获取到信息
        pageinfo<?> pageinfo = new pageinfo<>(searchproductdtos);
        // 封装为返回到前端分页组件可识别的视图
        val commonpagedresult = commonpagedresult.builder()
                .pagenumber(pagenumber)
                .rows(searchproductdtos)
                .totalpage(pageinfo.getpages())
                .records(pageinfo.gettotal())
                .build();
        return commonpagedresult;
    }

在这里,我们使用到了一个mybatis-pagehelper插件,会在下面的福利讲解中分解。

controller 实现

继续在com.liferunner.api.controller.productcontroller中添加对外暴露的接口api:

@getmapping("/searchbycategoryid")
    @apioperation(value = "查询商品信息列表", notes = "根据商品分类查询商品列表")
    public jsonresponse searchproductlistbycategoryid(
        @apiparam(name = "categoryid", value = "商品分类id", required = true, example = "0")
        @requestparam integer categoryid,
        @apiparam(name = "sortby", value = "排序方式", required = false)
        @requestparam string sortby,
        @apiparam(name = "pagenumber", value = "当前页码", required = false, example = "1")
        @requestparam integer pagenumber,
        @apiparam(name = "pagesize", value = "每页展示记录数", required = false, example = "10")
        @requestparam integer pagesize
    ) {
        if (null == categoryid || categoryid == 0) {
            return jsonresponse.errormsg("分类id错误!");
        }
        if (null == pagenumber || 0 == pagenumber) {
            pagenumber = default_page_number;
        }
        if (null == pagesize || 0 == pagesize) {
            pagesize = default_page_size;
        }
        log.info("============根据分类:{} 搜索列表==============", categoryid);

        val searchresult = this.productservice.searchproductlist(categoryid, sortby, pagenumber, pagesize);
        return jsonresponse.ok(searchresult);
    }

因为我们的请求中,只会要求商品分类id是必填项,其余的调用方都可以不提供,但是如果不提供的话,我们系统就需要给定一些默认的参数来保证我们的系统正常稳定的运行,因此,我定义了com.liferunner.api.controller.basecontroller,用于存储一些公共的配置信息。

/**
 * basecontroller for : controller 基类
 */
@controller
public class basecontroller {
    /**
     * 默认展示第1页
     */
    public final integer default_page_number = 1;
    /**
     * 默认每页展示10条数据
     */
    public final integer default_page_size = 10;
}

test api

测试的参数分别是:categoryid : 51 ,sortby : price,pagenumber : 1,pagesize : 5

[springboot 开发单体web shop] 7. 多种形式提供商品列表

可以看到,我们查询到7条数据,总页数totalpage为2,并且根据价格从小到大进行了排序,证明我们的编码是正确的。接下来,通过相同的代码逻辑,我们继续实现根据搜索关键词进行查询。

根据关键词查询

response dto 实现

使用上面实现的com.liferunner.dto.searchproductdto.

custom mapper 实现

com.liferunner.custom.productcustommapper中新增方法:

list<searchproductdto> searchproductlist(@param("parammap") map<string, object> parammap);

mapper/custom/productcustommapper.xml中添加查询sql:

<select id="searchproductlist" resulttype="com.liferunner.dto.searchproductdto" parametertype="map">
        select
        p.id as productid,
        p.product_name as productname,
        p.sell_counts as sellcounts,
        pi.url as imgurl,
        tp.pricediscount
        from products p
        left join products_img pi
        on p.id = pi.product_id
        left join
        (
        select product_id, min(price_discount) as pricediscount
        from products_spec
        group by product_id
        ) tp
        on tp.product_id = p.id
        where pi.is_main = 1
        <if test="parammap.keyword != null and parammap.keyword != ''">
            and p.item_name like "%${parammap.keyword}%"
        </if>
        order by
        <choose>
            <when test="parammap.sortby != null and parammap.sortby == 'sell'">
                p.sell_counts desc
            </when>
            <when test="parammap.sortby != null and parammap.sortby == 'price'">
                tp.pricediscount asc
            </when>
            <otherwise>
                p.created_time desc
            </otherwise>
        </choose>
    </select>

service 实现

com.liferunner.service.iproductservice中新增查询接口:

    /**
     * 查询商品列表
     *
     * @param keyword    查询关键词
     * @param sortby     排序方式
     * @param pagenumber 当前页码
     * @param pagesize   每页展示多少条数据
     * @return 通用分页结果视图
     */
    commonpagedresult searchproductlist(string keyword, string sortby, integer pagenumber, integer pagesize);

com.liferunner.service.impl.productserviceimpl实现上述接口方法:

    @override
    public commonpagedresult searchproductlist(string keyword, string sortby, integer pagenumber, integer pagesize) {
        map<string, object> parammap = new hashmap<>();
        parammap.put("keyword", keyword);
        parammap.put("sortby", sortby);
        // mybatis-pagehelper
        pagehelper.startpage(pagenumber, pagesize);
        val searchproductdtos = this.productcustommapper.searchproductlist(parammap);
        // 获取mybatis插件中获取到信息
        pageinfo<?> pageinfo = new pageinfo<>(searchproductdtos);
        // 封装为返回到前端分页组件可识别的视图
        val commonpagedresult = commonpagedresult.builder()
                .pagenumber(pagenumber)
                .rows(searchproductdtos)
                .totalpage(pageinfo.getpages())
                .records(pageinfo.gettotal())
                .build();
        return commonpagedresult;
    }

上述方法和之前searchproductlist(integer categoryid, string sortby, integer pagenumber, integer pagesize)唯一的区别就是它是肯定搜索关键词来进行数据查询,使用重载的目的是为了我们后续不同类型的业务扩展而考虑的。

controller 实现

com.liferunner.api.controller.productcontroller中添加关键词搜索api:

    @getmapping("/search")
    @apioperation(value = "查询商品信息列表", notes = "查询商品信息列表")
    public jsonresponse searchproductlist(
        @apiparam(name = "keyword", value = "搜索关键词", required = true)
        @requestparam string keyword,
        @apiparam(name = "sortby", value = "排序方式", required = false)
        @requestparam string sortby,
        @apiparam(name = "pagenumber", value = "当前页码", required = false, example = "1")
        @requestparam integer pagenumber,
        @apiparam(name = "pagesize", value = "每页展示记录数", required = false, example = "10")
        @requestparam integer pagesize
    ) {
        if (stringutils.isblank(keyword)) {
            return jsonresponse.errormsg("搜索关键词不能为空!");
        }
        if (null == pagenumber || 0 == pagenumber) {
            pagenumber = default_page_number;
        }
        if (null == pagesize || 0 == pagesize) {
            pagesize = default_page_size;
        }
        log.info("============根据关键词:{} 搜索列表==============", keyword);

        val searchresult = this.productservice.searchproductlist(keyword, sortby, pagenumber, pagesize);
        return jsonresponse.ok(searchresult);
    }

test api

测试参数:keyword : 西凤,sortby : sell,pagenumber : 1,pagesize : 10
[springboot 开发单体web shop] 7. 多种形式提供商品列表
根据销量排序正常,查询关键词正常,总条数32,每页10条,总共3页正常。

福利讲解

在本节编码实现中,我们使用到了一个通用的mybatis分页插件mybatis-pagehelper,接下来,我们来了解一下这个插件的基本情况。

mybatis-pagehelper

如果各位小伙伴使用过:mybatis 分页插件 pagehelper, 那么对于这个就很容易理解了,它其实就是基于executor 拦截器来实现的,当拦截到原始sql之后,对sql进行一次改造处理。
我们来看看我们自己代码中的实现,根据springboot编码三部曲:

1.添加依赖

        <!-- 引入mybatis-pagehelper 插件-->
        <dependency>
            <groupid>com.github.pagehelper</groupid>
            <artifactid>pagehelper-spring-boot-starter</artifactid>
            <version>1.2.12</version>
        </dependency>

有同学就要问了,为什么引入的这个依赖和我原来使用的不同?以前使用的是:

<dependency>
    <groupid>com.github.pagehelper</groupid>
    <artifactid>pagehelper</artifactid>
    <version>5.1.10</version>
</dependency>

答案就在这里:
[springboot 开发单体web shop] 7. 多种形式提供商品列表
我们使用的是springboot进行的项目开发,既然使用的是springboot,那我们完全可以用到它的自动装配特性,作者帮我们实现了这么一个,我们只需要参考示例来编写就ok了。

2.改配置

# mybatis 分页组件配置
pagehelper:
  helperdialect: mysql #插件支持12种数据库,选择类型
  supportmethodsarguments: true

3.改代码

如下示例代码:

    @override
    public commonpagedresult searchproductlist(string keyword, string sortby, integer pagenumber, integer pagesize) {
        map<string, object> parammap = new hashmap<>();
        parammap.put("keyword", keyword);
        parammap.put("sortby", sortby);
        // mybatis-pagehelper
        pagehelper.startpage(pagenumber, pagesize);
        val searchproductdtos = this.productcustommapper.searchproductlist(parammap);
        // 获取mybatis插件中获取到信息
        pageinfo<?> pageinfo = new pageinfo<>(searchproductdtos);
        // 封装为返回到前端分页组件可识别的视图
        val commonpagedresult = commonpagedresult.builder()
                .pagenumber(pagenumber)
                .rows(searchproductdtos)
                .totalpage(pageinfo.getpages())
                .records(pageinfo.gettotal())
                .build();
        return commonpagedresult;
    }

在我们查询数据库之前,我们引入了一句pagehelper.startpage(pagenumber, pagesize);,告诉mybatis我们要对查询进行分页处理,这个时候插件会启动一个拦截器com.github.pagehelper.pageinterceptor,针对所有的query进行拦截,添加自定义参数和添加查询数据总数。(后续我们会打印sql来证明。)

当查询到结果之后,我们需要将我们查询到的结果通知给插件,也就是pageinfo<?> pageinfo = new pageinfo<>(searchproductdtos);com.github.pagehelper.pageinfo是对插件针对分页做的一个属性包装,具体可以查看)。

至此,我们的插件使用就已经结束了。但是为什么我们在后面又封装了一个对象来对外进行返回,而不是使用查询到的pageinfo呢?这是因为我们实际开发过程中,为了数据结构的一致性做的一次结构封装,你也可不实现该步骤,都是对结果没有任何影响的。

sql打印对比

2019-11-21 12:04:21 info  productcontroller:134 - ============根据关键词:西凤 搜索列表==============
creating a new sqlsession
sqlsession [org.apache.ibatis.session.defaults.defaultsqlsession@4ff449ba] was not registered for synchronization because synchronization is not active
jdbc connection [hikariproxyconnection@1980420239 wrapping com.mysql.cj.jdbc.connectionimpl@563b22b1] will not be managed by spring
==>  preparing: select count(0) from products p left join products_img pi on p.id = pi.product_id left join (select product_id, min(price_discount) as pricediscount from products_spec group by product_id) tp on tp.product_id = p.id where pi.is_main = 1 and p.product_name like "%西凤%" 
==> parameters: 
<==    columns: count(0)
<==        row: 32
<==      total: 1
==>  preparing: select p.id as productid, p.product_name as productname, p.sell_counts as sellcounts, pi.url as imgurl, tp.pricediscount from product p left join products_img pi on p.id = pi.product_id left join ( select product_id, min(price_discount) as pricediscount from products_spec group by product_id ) tp on tp.product_id = p.id where pi.is_main = 1 and p.product_name like "%西凤%" order by p.sell_counts desc limit ? 
==> parameters: 10(integer)

我们可以看到,我们的sql中多了一个select count(0),第二条sql多了一个limit参数,在代码中,我们很明确的知道,我们并没有显示的去搜索总数和查询条数,可以确定它就是插件帮我们实现的。

源码下载

github 传送门
gitee 传送门

下节预告

下一节我们将继续开发商品详情展示以及商品评价业务,在过程中使用到的任何开发组件,我都会通过专门的一节来进行介绍的,兄弟们末慌!

gogogo!