Make writing a habit together! This is the fourth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Hot seller list

1 Goods – Create data table

1. Run the use command to select the store database.

USE store;
Copy the code

2. Create the T_product table in the Store database.

CREATE TABLE t_product (
  id int(20) NOT NULL COMMENT 'commodity id',
  category_id int(20) DEFAULT NULL COMMENT 'category id',
  item_type varchar(100) DEFAULT NULL COMMENT 'Merchandise Series',
  title varchar(100) DEFAULT NULL COMMENT 'Commodity title',
  sell_point varchar(150) DEFAULT NULL COMMENT 'Selling point',
  price bigint(20) DEFAULT NULL COMMENT 'Unit price of goods'.num int(10) DEFAULT NULL COMMENT 'Stock quantity',
  image varchar(500) DEFAULT NULL COMMENT 'Picture path'.status int(1) DEFAULT '1' COMMENT 'Product Status 1: Shelves 2: Shelves removed 3: Deleted'.priority int(10) DEFAULT NULL COMMENT 'Show priority',
  created_time datetime DEFAULT NULL COMMENT 'Creation time',
  modified_time datetime DEFAULT NULL COMMENT 'Last modified time',
  created_user varchar(50) DEFAULT NULL COMMENT 'Founder',
  modified_user varchar(50) DEFAULT NULL COMMENT 'Last Modifier',
  PRIMARY KEY (id))ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code

2 Goods – Create entity class

Create com. Cy. Store. The entity. The Product class, and inherited from BaseEntity class. Declare attributes in the class that correspond to those in the data table.

package com.cy.store.entity;

/** Entity class of commodity data */
public class Product extends BaseEntity implements Serializable {
    private Integer id;
    private Integer categoryId;
    private String itemType;
    private String title;
    private String sellPoint;
    private Long price;
    private Integer num;
    private String image;
    private Integer status;
    private Integer priority;

    // Generate: Getter and Setter, Generate hashCode() and equals(), toString()
}
Copy the code

3 Goods – Hot Seller Ranking – Persistence layer

3.1 Planning SQL Statements to Be Executed

The SQL statement to query the list of hot items is roughly.

SELECT * FROM t_product WHERE status=1 ORDER BY priority DESC LIMIT 0.4
Copy the code

3.2 Interfaces and abstract methods

Create the ProductMapper interface in the com.cy.store.mapper package and add a method to the ProductMapper interface to query the hot commodity findHotList().

package com.cy.store.mapper;
import com.cy.store.entity.Product;
import java.util.List;

/** Persistence layer interface for processing commodity data */
public interface ProductMapper {
    /** ** query top 4 items * @return top 4 items collection */
    List<Product> findHotList();
}
Copy the code

3.3 Configuring SQL Mapping

1. Create the productmapper. XML file in the main\ Resources \mapper folder and configure the findHotList() method mapping in the file.


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.store.mapper.ProductMapper">
    <resultMap id="ProductEntityMap" type="com.cy.store.entity.Product">
        <id column="id" property="id"/>
        <result column="category_id" property="categoryId"/>
        <result column="item_type" property="itemType"/>
        <result column="sell_point" property="sellPoint"/>
        <result column="created_user" property="createdUser"/>
        <result column="created_time" property="createdTime"/>
        <result column="modified_user" property="modifiedUser"/>
        <result column="modified_time" property="modifiedTime"/>
    </resultMap>

    <! List<Product> findHostList() -->
    <select id="findHotList" resultMap="ProductEntityMap">
        SELECT
            *
        FROM
            t_product
        WHERE
            status=1
        ORDER BY
            priority DESC
            LIMIT 0,4
    </select>
</mapper>
Copy the code

2. Create the ProductMapperTests class in the com.cy.store.mapper package and add test methods.

package com.cy.store.mapper;
import com.cy.store.entity.Product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductMapperTests {
    @Autowired
    private ProductMapper productMapper;

    @Test
    public void findHotList(a) {
        List<Product> list = productMapper.findHotList();
        System.out.println("count=" + list.size());
        for(Product item : list) { System.out.println(item); }}}Copy the code

4 Merchandise – Top Selling – Business Tier

4.1 Planning Exceptions

Note: There is no exception.

4.2 Interfaces and Abstract Methods

Create com. Cy. Store. Service. IProductService interface, and add in the interface findHotList () method.

package com.cy.store.service;
import com.cy.store.entity.Product;
import java.util.List;

/** Business layer interface for processing commodity data */
public interface IProductService {
    /** * query top 4 items *@returnA collection of the top four hot items */
    List<Product> findHotList(a);
}
Copy the code

4.3 Implement abstract methods

1. Create com. Cy. Store. Service. Impl. ProductServiceImpl classes, and add @ service annotations; Declare persistence layer objects in classes and implement methods in interfaces.

package com.cy.store.service.impl;
import com.cy.store.entity.Product;
import com.cy.store.mapper.ProductMapper;
import com.cy.store.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/** Business layer implementation class for handling commodity data */
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<Product> findHotList(a) {
        List<Product> list = productMapper.findHotList();
        for (Product product : list) {
            product.setPriority(null);
            product.setCreatedUser(null);
            product.setCreatedTime(null);
            product.setModifiedUser(null);
            product.setModifiedTime(null);
        }
        returnlist; }}Copy the code

2. Create ProductServiceTests in the com.cy.store.service package and write test methods.

package com.cy.store.service;
import com.cy.store.entity.Product;
import com.cy.store.service.ex.ServiceException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductServiceTests {
    @Autowired
    private IProductService productService;

    @Test
    public void findHotList(a) {
        try {
            List<Product> list = productService.findHotList();
            System.out.println("count=" + list.size());
            for(Product item : list) { System.out.println(item); }}catch(ServiceException e) { System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); }}}Copy the code

5 Merchandise – Best-selling Rankings – Controllers

5.1 Handling Exceptions

Note: There is no exception.

5.2 Design Request

1. Design requests submitted by users, and design the way to respond.

Request path: /products/hot_list Request parameters: None Request type: GET Response result: JsonResult<List<Product>> Whether to block: No, add index.html and products/** to the whitelistCopy the code

2. The index in LoginInterceptorConfigurer class. HTML pages and products / * * request added to white list.

patterns.add("/web/index.html");
patterns.add("/products/**");
Copy the code

5.3 Processing Requests

1. Create com. Cy. Controller. ProductController class inherits from BaseController class, the class add @ RestController and @ RequestMapping annotations (” products “), and the business layer is added in the class object.

package com.cy.store.controller;
import com.cy.store.entity.Product;
import com.cy.store.service.IProductService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("products")
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;
}
Copy the code

2. Add the getHotList() method to the class to handle the request.

@RequestMapping("hot_list")
public JsonResult<List<Product>> getHotList() {
    List<Product> data = productService.findHotList();
    return new JsonResult<List<Product>>(OK, data);
}
Copy the code

3. Start after the completion of the project, direct access to the http://localhost:8080/products/hot_list for testing.

6 Merchandise – Top Selling – Front page

1. On the index. HTML page, set the ID attribute for the div tag in the Top Selling List.

<div id="hot-list" class="panel-body panel-item">
	<! -... -->
</div>
Copy the code

2. At the end of the body tag in the index. HTML page, add the code that displays the top selling items.

<script type="text/javascript">
$(document).ready(function() {
    showHotList();
});

function showHotList() {$("#hot-list").empty();
    $.ajax({
        url: "/products/hot_list".type: "GET".dataType: "JSON".success: function(json) {
            let list = json.data;
            console.log("count=" + list.length);
            for (let i = 0; i < list.length; i++) {
                console.log(list[i].title);
                let html = '<div class="col-md-12">'
                  + '
      '
                  + '< div class = "col - md - 2" > selections # {price} < / div >'
                  + '
      
'
+ '</div>'; html = html.replace(/#{id}/g, list[i].id); html = html.replace(/#{title}/g, list[i].title); html = html.replace(/#{price}/g, list[i].price); html = html.replace(/#{image}/g, list[i].image); $("#hot-list").append(html); }}}); } </script>Copy the code

3. Start after the completion of the project, direct access to the http://localhost:8080/web/index.html for testing.

Display of goods

1 Item – Displays item details – Persistence layer

1.1 Planning SQL Statements to Be Executed

The SQL statement that displays the details of the item based on the item ID is roughly.

SELECT * FROM t_product WHERE id=?
Copy the code

1.2 Interfaces and Abstract methods

Add abstract methods to the ProductMapper interface.

/** * Query the product details based on the product id *@paramId Id of the product *@returnMatching item details, or null */ if there is no matching data
Product findById(Integer id);
Copy the code

1.3 Configuring SQL Mapping

1. In the productmapper. XML file, configure the mapping of the findById(Integer ID) method.

<! Product findById(Integer ID) -->
<select id="findById" resultMap="ProductEntityMap">
    SELECT
    	*
    FROM
    	t_product
    WHERE
    	id=#{id}
</select>
Copy the code

2. Add test methods to the ProductMapperTests test class.

@Test
public void findById(a) {
    Integer id = 10000017;
    Product result = productMapper.findById(id);
    System.out.println(result);
}
Copy the code

2 Commodity – Displays commodity details – Business layer

2.1 Abnormal Planning

Data does not exist, if the goods should be thrown ProductNotFoundException, need to create a com. Cy. Store. Service. Ex. ProductNotFoundException anomalies.

package com.cy.store.service.ex;

/** The commodity data does not exist */
public class ProductNotFoundException extends ServiceException {
    // Override Methods...
}
Copy the code

2.2 Interfaces and Abstract methods

Add the findById(Integer ID) abstract method to the business layer IProductService interface.

/** * Query the product details based on the product id *@paramId Id of the product *@returnMatching item details, or null */ if there is no matching data
Product findById(Integer id);
Copy the code

2.3 Implement abstract methods

1. Implement the findById(Integer ID) abstract method in the ProductServiceImpl class.

@Override
public Product findById(Integer id) {
    // Call the private method with the parameter ID to execute the query and get the commodity data
    Product product = productMapper.findById(id);
    // Check whether the query result is null
    if (product == null) {
        // Yes: Throw ProductNotFoundException
        throw new ProductNotFoundException("Attempted access to commodity data does not exist");
    }
    // Set some attributes in the query result to NULL
    product.setPriority(null);
    product.setCreatedUser(null);
    product.setCreatedTime(null);
    product.setModifiedUser(null);
    product.setModifiedTime(null);
    // Return the query result
    return product;
}
Copy the code

2. Write test methods in the ProductServiceTests test class.

@Test
public void findById(a) {
    try {
        Integer id = 100000179;
        Product result = productService.findById(id);
        System.out.println(result);
    } catch(ServiceException e) { System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); }}Copy the code

3 Merchandise – Display merchandise details – controller

3.1 Troubleshooting exceptions

Add an exception to handle ProductNotFoundException in the handleException() method of the BaseController class.

// ...
else if (e instanceof ProductNotFoundException) {
	result.setState(4006);
}
// ...
Copy the code

3.2 Design Request

Design requests submitted by users and design how they respond.

Request path: /products/{id}/details Request parameter: @pathvariable (" ID ") Integer ID Request type: GET Response result: JsonResult<Product>Copy the code

3.3 Processing Requests

1. Add a getById() method to handle requests in the ProductController class.

@GetMapping("{id}/details")
public JsonResult<Product> getById(@PathVariable("id") Integer id) {
    // Call business object execution to fetch data
    Product data = productService.findById(id);
    // Returns success and data
    return new JsonResult<Product>(OK, data);
}
Copy the code

2. Start after the completion of the project, direct access to the http://localhost:8080/products/10000017/details for testing.

4 Product – Display product details – front page

1. Check whether the jquery-geturlparam. js file is imported at the end of the body tag of the product. HTML page.

<script type="text/javascript" src=".. /js/jquery-getUrlParam.js"></script>
Copy the code

2. Add the code to get the details of the current product at the end of the body tag in the product.html page.

<script type="text/javascript">
let id = $.getUrlParam("id");
console.log("id=" + id);
$(document).ready(function() {
    $.ajax({
        url: "/products/" + id + "/details".type: "GET".dataType: "JSON".success: function(json) {
            if (json.state == 200) {
                console.log("title=" + json.data.title);
                $("#product-title").html(json.data.title);
                $("#product-sell-point").html(json.data.sellPoint);
                $("#product-price").html(json.data.price);

                for (let i = 1; i <= 5; i++) {
                    $("#product-image-" + i + "-big").attr("src".".." + json.data.image + i + "_big.png");
                    $("#product-image-" + i).attr("src".".." + json.data.image + i + ".jpg"); }}else if (json.state == 4006) { // There is no exception in the commodity data
                location.href = "index.html";
            } else {
                alert("Failed to get commodity information!"+ json.message); }}}); }); </script>Copy the code

3. Start the project, after the completion of first visit http://localhost:8080/web/index.html

Page, and then click a sub-item in “Hot Seller ranking”, will jump to the product. HTML product details page, observe whether the page is loaded with the current product information.