当前位置:网站首页>Dark horse shopping mall ---1 Project introduction - environment construction

Dark horse shopping mall ---1 Project introduction - environment construction

2022-06-25 12:03:00 Shuaijie it God

Study address :https://download.csdn.net/download/Q2802020/12883464

The first 1 Chapter Frame building

Learning goals

  • Understand e-commerce
  • Understand Changgou architecture
  • Understand Changgou engineering structure
  • Changgou project construction
  • Build commodity micro services
  • Add, delete, modify and check the brand

1. Go into e-commerce

1.1 Analysis of e-commerce industry

In recent years , The world economy is undergoing a digital transformation , It has become a global consensus to vigorously develop the digital economy . The report of the 19th CPC National Congress clearly proposed to build “ Digital China ”“ Network power ”, China's digital economy has entered a new stage of development , The market size ranks second in the world , Deep integration of digital economy and real economy , It has effectively promoted the supply side structural reform . E-commerce is an important part of digital economy , It is the most active digital economy 、 One of the most concentrated forms of expression .2017 year , Under the joint promotion of the government and the market , The development of e-commerce in China pays more attention to efficiency 、 Quality and innovation , A series of new developments have been made , Expanding the digital economy 、 To build “ the Belt and Road ”、 To promote the revitalization of the countryside 、 Drive innovation and entrepreneurship 、 It has played an important role in promoting economic transformation and upgrading , It has become a new driving force for China's economic growth .
2017 year , The scale of e-commerce transactions in China continues to expand , And maintain a high-speed growth trend . According to the National Bureau of Statistics ,2017 The amount of e-commerce transactions in China reached 29.16 Trillion yuan , Year-on-year growth 11.7%; Online retail sales 7.18 Trillion yuan , Year-on-year growth 32.2%. The advantages of e-commerce in China are further expanded , The scale of online retail is the largest in the world 、 The industrial innovation vitality is leading in the world . data display , end 2017 end of the year , The number of online shopping users nationwide has reached 5.33 Billion , Year-on-year growth 14.3%; The amount of online payments made by non bank payment institutions reached 143.26 Trillion yuan , Year-on-year growth 44.32%; The business volume of national express service enterprises has been accumulated 400.6 Million pieces , Year-on-year growth 28%; The direct employment of e-commerce and the indirect employment have reached 4250 ten thousand people .

 

2018 Tmall's whole day transaction volume record

1.2 Technical features of e-commerce system

 

  • New technology

  • Wide range of Technology

  • Distributed

  • High concurrency 、 colony 、 Load balancing 、 High availability

  • Huge amounts of data

  • Business complex

  • System security

1.3 Major e-commerce modes

B2B

1
2
3
B2B ( Business to Business) It means that both the supplier and the seller of e-commerce transactions are merchants ( Or a company 、 company ), she ( He ) They use Internet technology or various business networking platforms , The process of completing a business transaction . E-commerce is modern  B2B marketing A specific major form of expression .

 Case study : Alibaba 、 hc360 

C2C

1
2
3
C2C namely  Customer(Consumer) to Customer(Consumer), It means the e-commerce behavior between consumers and individuals . Let's say a consumer has a computer , Trade over the Internet , Sell it to another consumer , This type of transaction is called C2C Electronic Commerce .

 Case study : TaoBao 、 ebay 、 Melon seed used car 

B2C

1
2
3
B2C yes Business-to-Customer Abbreviation , Its Chinese abbreviation is “ business-to-consumer ”.“ business-to-consumer ” It is a mode of electronic commerce , That is, commonly referred to as the direct consumer sales of products and services business retail model . This form of e-commerce is generally dominated by online retailing , Mainly by means of the Internet to carry out online sales activities .B2C That is, enterprises provide consumers with a new shopping environment through the Internet —— Online store , Consumers shop online through the Internet 、 Online payment and other consumer behavior .

 Case study : Vipshop 、 Le bee network 

C2B

1
2
3
4
5
C2B(Consumer to Business, Consumer to business ), It is a new business model in the era of Internet economy . This model changes the original producer ( Enterprises and institutions ) Relationships with consumers , It's a consumer contribution (Create Value),  Consumption value of enterprises and institutions (Consume Value).

C2B The pattern and the pattern of supply and demand that we know (DSM, Demand SupplyModel) On the contrary , real C2B  There should be consumer demand first and then enterprise production , That is, the first consumer demand , After that, the production enterprise organizes production according to the demand . Customizing products and prices for consumers according to their own needs , Or actively participate in product design 、 Production and pricing , product 、 Price and other highlights the personalized consumer demand , Production enterprises carry out customized production .

 Case study : Haier Mall 、  Shangpin house accessories 

O2O

1
2
3
O2O namely Online To Offline( Online and offline / Online to offline ), It is the combination of offline business opportunities and the Internet , Make the Internet a platform for offline transactions , The concept originated in the United States .O2O The concept is very broad , Both can involve line , Can involve again offline , It can be called O2O. Mainstream business management courses are all right O2O This new business model is introduced and concerned .

 Case study : Meituan 、 Hungry? 

F2C

F2C refer to Factory to customer, Namely from the manufacturer to the consumer electronic commerce pattern .

B2B2C

1
2
3
4
B2B2C It is an e-commerce type of online shopping business model ,B yes BUSINESS For short ,C yes CUSTOMER For short , first B A supplier of goods or services , the second B Refers to the enterprise engaged in electronic commerce ,C It's the consumer .

 Case study : Jingdong Mall 、 Tmall mall 
 notes : We 《 Changgou e-commerce system development 》 The course uses B2C Pattern , Later project practice 《 The development practice of e-commerce system of pinyougou 》 use B2B2C Pattern .

2. Changgou - Requirements analysis and system design

 

  •  

2.1 Demand analysis

Static prototype demonstration at the front desk of the website , open Information \ page \ The front desk \project-changgou-portal-fis3-master, home page index.html

Website management background static prototype Demo :http://czpm.itcast.cn/ Green orange backstage /#g=1&p= The background page

open Information \ page \ backstage \project-changgou-cmm-fis3-master\pages, home page all-medical-main.html

2.2 The system design

Changgou mall belongs to B2C E-commerce mode , Operators publish their products on the website , After member registration , Add items to the shopping cart on the website , And place an order , Complete online payment , Users can also participate in the second kill rush purchase .

2.2.1 Fore and aft end separation

The back end of the website is separated from the front end .

Former JavaWeb Most of the projects are java Programmers are both parents , And the front end , Back end . With the development of the times , Gradually, many small and large companies began to make the distinction between the front end and the back end more and more clear , The front end engineer is all about the front end , Back-end engineers focus on back-end things . It's just that there is a specialty in the art industry , If a person can do anything , After all, he is not good at anything .

For the back end java The engineer :

Focus on Design Patterns ,spring+springmvc,linux,mysql Transaction isolation and locking mechanism ,mongodb,http/tcp, Multithreading , Distributed architecture , Elastic computing architecture , Microservice architecture ,java performance optimization , And related project management .

For front end Engineers :

Concentrate on html5,css3,vuejs,webpack,nodejs,Google V8 engine ,javascript Multithreading , modularization , Section oriented programming , Design patterns , Browser compatibility , Performance optimization and so on .

In this course, we provide the front-end code of the management background supporting the project course , But I won't explain the content of the front end . In this way, we will focus more on ** Back end code ** On the development of !

2.2.2 Technology Architecture

2.2.3 System architecture diagram

3 Changgou - Frame building

3.1 Environmental preparation

(1)VMware Workstation Pro install centos7 Mirror image

(2) install docker

(3) Pull mySQL Mirror image , And create a container

(4) Client connection mysql Containers , Building database and building tables ( The database and table creation statements are provided in the resource folder )

Virtual machine data :

  • virtual machine IP:192.168.211.132

  • Virtual machine account :root password :123456

  • Database port :3306
  • Database account :root password :123456

Database script : Information \ Database script

3.2 Project structure description

Structure description :

changgou-gateway

 Gateway module , According to the size and needs of the website , Services related to integrated logic can be combined with gateway routing . You can also perform authentication and current limiting operations here .

changgou-service

 Microservice module , This module is used to store all independent microservice projects .

changgou-service_api

 Corresponding to the project JavaBean、Feign、 as well as Hystrix To configure , The project mainly relies on external supply .

changgou-transaction-fescar

 Distributed transaction module , Extract distributed transactions into the project , Any project that needs to use distributed transactions , Just rely on the project .

changgou-web

web Service Engineering , If the corresponding function module needs to call multiple microservices , They can be written into the module , For example, website background 、 Website front desk, etc 

3.3 Public works construction

3.3.1 Father project construction

Create parent project changgou-parent ,pom.xml Add configuration... To the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.changgou</groupId>
    <artifactId>changgou-parent</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <skipTests>true</skipTests>
    </properties>

    <!-- Dependency package -->
    <dependencies>
        <!-- Test package -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

        <!--swagger file -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

        <!--
            http://localhost:9011/swagger-ui.html
        -->
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Delete src Folder

3.3.2 Construction of other public modules

establish changgou-gateway、changgou-service、changgou-service-api、changgou-web engineering , The project is all pom engineering , And all of the works src File deletion .

pom.xml Hit middle pom package

<packaging>pom</packaging>

The project structure is as follows :

3.4 Eureka Micro service building

3.4.1 pom.xml rely on

Create a module changgou-eureka ,pom.xml Introduce dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>changgou_parent</artifactId>
        <groupId>com.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>changgou_eureka</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

3.4.2 appliation.yml To configure

create profile application.yml

1
2
3
4
5
6
7
8
9
10
server:
  port: 7001
eureka:
  instance:
    hostname: 127.0.0.1
  client:
    register-with-eureka: false   # Whether to register yourself with eureka in 
    fetch-registry: false         # Whether from eureka For information 
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

3.4.3 Start class configuration

Create a package com.changgou Create a startup class under the package EurekaApplication, The code is as follows :

The above code is as follows :

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class);
    }
}

Test access http://localhost:7001/, The effect is as follows :

3.5 Public module construction

3.5.1 pom.xml rely on

Create common sub module changgou-common,pom.xml Introduce dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>changgou-parent</artifactId>
        <groupId>com.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>changgou-common</artifactId>

    <dependencies>
        <!--web Start relying on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- redis  Use -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- Wechat payment -->
        <dependency>
            <groupId>com.github.wxpay</groupId>
            <artifactId>wxpay-sdk</artifactId>
            <version>0.0.3</version>
        </dependency>
        <!--httpclient Support -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
    </dependencies>
</project>

After the common sub module introduces these dependencies , Other micro services are introduced changgou-common These dependencies are also automatically introduced

3.5.2 Common objects

establish entity package , stay entity Create an entity class that returns the status code under the package

1
2
3
4
5
6
7
8
9
10
11
12
/**
 *  Return code 
 */
public class StatusCode {
    public static final int OK = 20000;// success 
    public static final int ERROR = 20001;// Failure 
    public static final int LOGINERROR = 20002;// Wrong user name or password 
    public static final int ACCESSERROR = 20003;// Insufficient authority 
    public static final int REMOTEERROR = 20004;// Remote call failed 
    public static final int REPERROR = 20005;// Repeat 
    public static final int NOTFOUNDERROR = 20006;// There is no corresponding rush purchase data 
}

Create classes under the package Result It is used for microservices to return results to the front end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 *  Return the result entity class 
 */
public class Result<T> {
    private boolean flag;// The success of 
    private Integer code;// Return code 
    private String message;// Return message 
    private T data;// Return the data 

    public Result(boolean flag, Integer code, String message, Object data) {
        this.flag = flag;
        this.code = code;
        this.message = message;
        this.data = (T) data;
    }

    public Result(boolean flag, Integer code, String message) {
        this.flag = flag;
        this.code = code;
        this.message = message;
    }

    public Result() {
        this.flag = true;
        this.code = StatusCode.OK;
        this.message = " Successful operation !";
    }

    // getter and setter.....
}

stay entity Create classes under the package to carry the paged data results

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 *  Paging result class 
 */
public class PageResult<T> {

    private Long total;// Total number of records 
    private List<T> rows;// Record 

    public PageResult(Long total, List<T> rows) {
        this.total = total;
        this.rows = rows;
    }

    public PageResult() {
    }

    //getter and setter ......
}

Of course , We can also put other tool classes into the project together , It will be used later , take Information \ Tool class All classes in are imported directly into entity It's a bag .

3.6 Data access engineering construction

Create common modules changgou-common-db ,pom File import dependency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>changgou-parent</artifactId>
        <groupId>com.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>changgou-common-db</artifactId>

    <!-- rely on -->
    <dependencies>
        <!-- Yes changgou-common Dependence -->
        <dependency>
            <groupId>com.changgou</groupId>
            <artifactId>changgou-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- Universal mapper Start relying on -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--MySQL Database driven -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis Paging plug-ins -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>
</project>

This common module is the connection mysql The public microservice module of the database , So you need to connect mysql All of the microservices are inherited from this project .

3.7 Build commodity micro services

 

  •  

The commodity micro service is mainly used to add, delete, modify and query commodities , And the addition, deletion, modification and query of commodity related information .

3.7.1 Construction of common component works

establish changgou-service-api Sub module changgou-service-goods-api, And will Information \javabean\changgou-service-goods-api Medium Pojo Import into project .

Modify parent project changgou-service-api Of pom.xml, add to persistence-api and changgou-common Dependence , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependencies>
    <!-- General purpose common-->
    <dependency>
        <groupId>com.changgou</groupId>
        <artifactId>changgou-common</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <!-- Every project has Pojo, You need to use the corresponding annotation of the package -->
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

3.7.2 Microservice engineering construction

modify changgou-service Of pom.xml introduce changgou-common-db Dependence , The code is as follows :

1
2
3
4
5
6
7
8
<!-- rely on -->
<dependencies>
    <dependency>
        <groupId>com.changgou</groupId>
        <artifactId>changgou-common-db</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

stay changgou-service Created in changgou-service-goods ,pom.xml Introduce dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>changgou-service</artifactId>
        <groupId>com.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>changgou-service-goods</artifactId>

    <!-- rely on -->
    <dependencies>
        <dependency>
            <groupId>com.changgou</groupId>
            <artifactId>changgou-service-goods-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

stay resources Create profile under application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
server:
  port: 18081
spring:
  application:
    name: goods
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.211.132:3306/changgou_goods?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:7001/eureka
  instance:
    prefer-ip-address: true
feign:
  hystrix:
    enabled: true
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.changgou.goods.pojo

In the bag com.changgou.goods Create a startup class under the package GoodsApplication, The code is as follows :

The above code is as follows :

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableEurekaClient
@MapperScan(basePackages = {"com.changgou.goods.dao"})
public class GoodsApplication {
    public static void main(String[] args) {
        SpringApplication.run(GoodsApplication.class);
    }
}

Be careful  :@MapperScan yes tk.mybatis.spring.annotation Under bag , For scanning Mapper Interface

start-up changgou-service-goods  Revisit <http://localhost:7001/> The effect is as follows :

==4 Commodity micro service - Add, delete, modify and check the brand ==

4.1 Demand analysis

Create a commodity micro service , Add, delete, modify and query the brand table . Specific include

(1) Query all list data

(2) according to ID Query entity data

(3) increase

(4) modify

(5) Delete

(6) Conditions of the query

(7) Paging query

(8) Pagination + Conditions of the query

(9) Public exception handling

4.2 Table structure analysis

Brand list :tb_brand

Field name Field meaning Field type Field length remarks
id brand idINT  
name The brand name VARCHAR  
image Brand image address VARCHAR  
letter The initials of the brand CHAR  
seq Sort INT  

4.3 Code implementation

The above brand table corresponds to Brand Entity class

1
2
3
4
5
6
7
8
9
10
11
@Table(name="tb_brand")
public class Brand implements Serializable{
	@Id
	private Integer id;// brand id
	private String name;// The brand name 
	private String image;// Brand image address 
	private String letter;// The initials of the brand 
	private Integer seq;// Sort 
	
	// getter and setter  .....( Omit )
}

@Table and @Id All are JPA annotation ,@Table Used to configure the mapping relationship between tables and entity classes ,@Id Used to identify the primary key attribute .

4.3.1 Brand list

(1)Dao establish

stay changgou-service-goods Create under microservices com.changgou.goods.dao.BrandMapper Interface , The code is as follows :

1
2
public interface BrandMapper extends Mapper<Brand> {
}

Inherited Mapper Interface , It automatically implements the common methods of adding, deleting, modifying and querying .

(2) The business layer

establish com.changgou.goods.service.BrandService Interface , The code is as follows :

1
2
3
4
5
6
7
8
public interface BrandService {

    /***
     *  Check all brands 
     * @return
     */
    List<Brand> findAll();
}

establish com.changgou.goods.service.impl.BrandServiceImpl Implementation class , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service
public class BrandServiceImpl {

    @Autowired
    private BrandMapper brandMapper;

    /**
     *  All data 
     * @return
     */
    public List<Brand> findAll(){
        return brandMapper.selectAll();
    }
}

(3) Control layer

Control layer com.changgou.goods Package created under controller package , Create class under package

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/brand")
@CrossOrigin
public class BrandController {

    @Autowired
    private BrandService brandService;

    /***
     *  Query all data 
     * @return
     */
    @GetMapping
    public Result<Brand> findAll(){
        List<Brand> brandList = brandService.findAll();
        return new Result<Brand>(true, StatusCode.OK," The query is successful ",brandList) ;
    }
}

test :http://localhost:18081/brand

4.3.2 according to ID Search for brands

(1) The business layer

modify com.changgou.goods.service.BrandService Interface , Add according to ID How to query brand data , The code is as follows :

1
2
3
4
5
6
/**
 *  according to ID Inquire about 
 * @param id
 * @return
 */
Brand findById(Integer id);

modify com.changgou.goods.service.impl.BrandServiceImpl The new method , The code is as follows :

1
2
3
4
5
6
7
8
9
/**
 *  according to ID Inquire about 
 * @param id
 * @return
 */
@Override
public Brand findById(Integer id){
    return  brandMapper.selectByPrimaryKey(id);
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
11
/***
 *  according to ID Query brand data 
 * @param id
 * @return
 */
@GetMapping("/{id}")
public Result<Brand> findById(@PathVariable Integer id){
    // according to ID Inquire about 
    Brand brand = brandService.findById(id);
    return new Result<Brand>(true,StatusCode.OK," The query is successful ",brand);
}

test :http://localhost:18081/brand/14026

4.3.3 New brands

(1) The business layer

modify com.changgou.goods.service.BrandService, The new method

1
2
3
4
5
/***
 *  New brands 
 * @param brand
 */
void add(Brand brand);

modify com.changgou.goods.service.impl.BrandServiceImpl, The new brand method code is as follows :

1
2
3
4
5
6
7
8
/**
 *  increase 
 * @param brand
 */
@Override
public void add(Brand brand){
    brandMapper.insertSelective(brand);
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
/***
 *  New brand data 
 * @param brand
 * @return
 */
@PostMapping
public Result add(@RequestBody Brand brand){
    brandService.add(brand);
    return new Result(true,StatusCode.OK," Add success ");
}

test :http://localhost:18081/brand

4.3.4 Brand revision

(1) The business layer

Need to change com.changgou.goods.service.BrandService, Add and modify brand methods , The code is as follows :

1
2
3
4
5
/***
 *  Modify brand data 
 * @param brand
 */
void update(Brand brand);

modify com.changgou.goods.service.impl.BrandServiceImpl, Add and modify brand methods , The code is as follows :

1
2
3
4
5
6
7
8
/**
 *  modify 
 * @param brand
 */
@Override
public void update(Brand brand){
    brandMapper.updateByPrimaryKeySelective(brand);
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/***
 *  Modify brand data 
 * @param brand
 * @param id
 * @return
 */
@PutMapping(value="/{id}")
public Result update(@RequestBody Brand brand,@PathVariable Integer id){
    // Set up ID
    brand.setId(id);
    // Modifying data 
    brandService.update(brand);
    return new Result(true,StatusCode.OK," Modification successful ");
}

test :http://localhost:18081/brand/325415

4.3.5 Delete brand

(1) The business layer

modify com.changgou.goods.service.BrandService, Add or remove branding methods , The code is as follows :

1
2
3
4
5
/***
 *  Delete brand 
 * @param id
 */
void delete(Integer id);

modify com.changgou.goods.service.impl.BrandServiceImpl, Add and delete brand method , The code is as follows :

1
2
3
4
5
6
7
8
/**
 *  Delete 
 * @param id
 */
@Override
public void delete(Integer id){
    brandMapper.deleteByPrimaryKey(id);
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
/***
 *  according to ID Delete brand data 
 * @param id
 * @return
 */
@DeleteMapping(value = "/{id}" )
public Result delete(@PathVariable Integer id){
    brandService.delete(id);
    return new Result(true,StatusCode.OK," Delete successful ");
}

test :http://localhost:18081/brand/325415

4.3.6 Brand list condition query

(1) The business layer

modify com.changgou.goods.service.BrandService, Add the method of searching brands according to conditions , The code is as follows :

1
2
3
4
5
6
/***
 *  Multi criteria search brand method 
 * @param brand
 * @return
 */
List<Brand> findList(Brand brand);

modify com.changgou.goods.service.impl.BrandServiceImpl, Add the implementation of the brand search method based on multiple conditions , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 *  Conditions of the query 
 * @param brand
 * @return
 */
@Override
public List<Brand> findList(Brand brand){
    // Build query criteria 
    Example example = createExample(brand);
    // Query the data according to the constructed conditions 
    return brandMapper.selectByExample(example);
}


/**
 *  Building query objects 
 * @param brand
 * @return
 */
public Example createExample(Brand brand){
    Example example=new Example(Brand.class);
    Example.Criteria criteria = example.createCriteria();
    if(brand!=null){
        //  The brand name 
        if(!StringUtils.isEmpty(brand.getName())){
            criteria.andLike("name","%"+brand.getName()+"%");
        }
        //  Brand image address 
        if(!StringUtils.isEmpty(brand.getImage())){
            criteria.andLike("image","%"+brand.getImage()+"%");
        }
        //  The initials of the brand 
        if(!StringUtils.isEmpty(brand.getLetter())){
            criteria.andLike("letter","%"+brand.getLetter()+"%");
        }
        //  brand id
        if(!StringUtils.isEmpty(brand.getLetter())){
            criteria.andEqualTo("id",brand.getId());
        }
        //  Sort 
        if(!StringUtils.isEmpty(brand.getSeq())){
            criteria.andEqualTo("seq",brand.getSeq());
        }
    }
    return example;
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
/***
 *  Multi criteria search for brand data 
 * @param brand
 * @return
 */
@PostMapping(value = "/search" )
public Result<List<Brand>> findList(@RequestBody(required = false) Brand brand){
    List<Brand> list = brandService.findList(brand);
    return new Result<List<Brand>>(true,StatusCode.OK," The query is successful ",list);
}

test :http://localhost:18081/brand/search

4.3.7 Query the brand list by page

(1) The business layer

modify com.changgou.goods.service.BrandService Add paging method , The code is as follows :

1
2
3
4
5
6
7
/***
 *  Paging query 
 * @param page
 * @param size
 * @return
 */
PageInfo<Brand> findPage(int page, int size);

modify com.changgou.goods.service.impl.BrandServiceImpl Add paging method implementation , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 *  Paging query 
 * @param page
 * @param size
 * @return
 */
@Override
public PageInfo<Brand> findPage(int page, int size){
    // Static paging 
    PageHelper.startPage(page,size);
    // Paging query 
    return new PageInfo<Brand>(brandMapper.selectAll());
}

(2) Control layer

BrandController The new method

1
2
3
4
5
6
7
8
9
10
11
12
/***
 *  Paging search implementation 
 * @param page: The current page 
 * @param size: How many items are displayed per page 
 * @return
 */
@GetMapping(value = "/search/{page}/{size}" )
public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
    // Paging query 
    PageInfo<Brand> pageInfo = brandService.findPage(page, size);
    return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
}

test :http://localhost:18081/brand/search/1/3

4.3.8 Brand list conditions + Paging query

(1) The business layer

modify com.changgou.goods.service.BrandService, Add multi condition paging query method , The code is as follows :

1
2
3
4
5
6
7
8
/***
 *  Multi conditional paging query 
 * @param brand
 * @param page
 * @param size
 * @return
 */
PageInfo<Brand> findPage(Brand brand, int page, int size);

modify com.changgou.goods.service.impl.BrandServiceImpl, The code for adding a multi condition paging query method is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 *  Conditions + Paging query 
 * @param brand  Query criteria 
 * @param page  Page number 
 * @param size  Page size 
 * @return  Paging results 
 */
@Override
public PageInfo<Brand> findPage(Brand brand, int page, int size){
    // Pagination 
    PageHelper.startPage(page,size);
    // Search term construction 
    Example example = createExample(brand);
    // Execution search 
    return new PageInfo<Brand>(brandMapper.selectByExample(example));
}

(2) Control layer

 

  •  

BrandController The new method

1
2
3
4
5
6
7
8
9
10
11
12
13
/***
 *  Paging search implementation 
 * @param brand
 * @param page
 * @param size
 * @return
 */
@PostMapping(value = "/search/{page}/{size}" )
public Result<PageInfo> findPage(@RequestBody(required = false) Brand brand, @PathVariable  int page, @PathVariable  int size){
    // Execution search 
    PageInfo<Brand> pageInfo = brandService.findPage(brand, page, size);
    return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
}

test :http://localhost:18081/brand/search/1/3

4.3.9 Public exception handling

To make our code easier to maintain , Let's create a class to handle exceptions , This exception class can be created in changgou-common In Engineering , establish com.changgou.framework.exception.BaseExceptionHandler, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@ControllerAdvice
public class BaseExceptionHandler {

    /***
     *  exception handling 
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR, e.getMessage());
    }
}

Be careful :@ControllerAdvice annotation , Global capture exception class , As long as it acts on @RequestMapping On , All exceptions will be caught .

原网站

版权声明
本文为[Shuaijie it God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251145207397.html