This paper mainly explains the integration of Mall SpringBoot+MyBatis to build the basic skeleton, take the commodity brand as an example to achieve the basic CRUD operation and through PageHelper to achieve paging query.

Set up the mysql database environment

  • Download and install mysql5.7 version, the download address: dev.mysql.com/downloads/i…
  • Set the database account password to root root
  • Download and install the client connection tool Navicat, download address: www.formysql.com/xiazai.html
  • Create database Mall
  • Import the database script of the mall at github.com/macrozheng/…

Introduction to the project usage framework

SpringBoot

SpringBoot allows you to quickly build Spring-based Web applications with built-in Web containers (such as Tomcat) that run by starting the entry program’s main function.

PagerHelper

MyBatis paging plug-in, simple a few lines of code can achieve paging, when integrating with SpringBoot, as long as the integration of PagerHelper will automatically integrate MyBatis.

PageHelper.startPage(pageNum, pageSize);
// After the query operation will automatically paging
List<PmsBrand> brandList = brandMapper.selectByExample(new PmsBrandExample());
// Construct the PageInfo object to get the page information, such as the current page number, total pages, total number of pages
PageInfo<PmsBrand> pageInfo = new PageInfo<PmsBrand>(list);
Copy the code

Druid

Alibaba’s open source database connection pool claims to be the best in the Java language.

Mybatis generator

MyBatis code generator, can generate model, mapper. XML, Mapper interface and Example according to the database, usually the single table query does not need to write mapper.

Project structures,

Initialize a SpringBoot project with IDEA

Adding project dependencies

Add dependencies in pom.xml.

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>
    <dependencies>
        <! --SpringBoot Universal Dependency module -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <! --MyBatis paging plugin -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
        <! -- Integrate druid connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <! -- MyBatis generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.3</version>
        </dependency>
        <! --Mysql database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
    </dependencies>
Copy the code

Example Modify the SpringBoot configuration file

Add data source configuration and MyBatis’ mapper. XML path configuration to application.yml.

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
    - classpath*:com/**/mapper/*.xml
Copy the code

Project Structure Description

Mybatis Generator configuration file

To configure the database connection, Mybatis Generator generates the path to the Model, mapper interface, and mapper. XML.

<?xml version="1.0" encoding="UTF-8"? >

      

<generatorConfiguration>
    <properties resource="generator.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <! -- Generate serialization methods for the model -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <! Create a toString method for the generated Java model -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <! -- You can customize code comments to generate model -->
        <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">
            <! -- Whether to remove automatically generated comments true: yes: false: no -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <! -- configure database connection -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <! -- Fixed mysql driver upgrade to 8.0 not generating specified database code -->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <! -- specify the path to generate the model -->
        <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-01\src\main\java"/>
        <! -- specify the path to generate mapper.xml -->
        <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-01\src\main\resources"/>
        <! -- specify the path where the mapper interface is generated -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"
                             targetProject="mall-tiny-01\src\main\java"/>
        <!--生成全部表tableName设为%-->
        <table tableName="pms_brand">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
Copy the code

Run the Generator’s main function to generate the code

package com.macro.mall.tiny.mbg;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/** ** create by Macro on 2018/4/26. */
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG execution warning message
        List<String> warnings = new ArrayList<String>();
        // Overwrite the original code when the generated code is repeated
        boolean overwrite = true;
        // Read our MBG configuration file
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        / / create the MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        // Execute the generated code
        myBatisGenerator.generate(null);
        // Output a warning message
        for(String warning : warnings) { System.out.println(warning); }}}Copy the code

Add the Java configuration for MyBatis

This parameter is used to configure the path of the mapper interface that needs to be dynamically generated

package com.macro.mall.tiny.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/** * MyBatis configuration class * Created by Macro on 2019/4/8
@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {}Copy the code

Implement the interfaces in Controller

PmsBrand table to add, modify, delete and paging query interface.

package com.macro.mall.tiny.controller;

import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.service.PmsBrandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/** * Brand management Controller * Created by Macro on 2019/4/19. */
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    private PmsBrandService demoService;

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);

    @RequestMapping(value = "listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<PmsBrand>> getBrandList() {
        return CommonResult.success(demoService.listAllBrand());
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
        CommonResult commonResult;
        int count = demoService.createBrand(pmsBrand);
        if (count == 1) {
            commonResult = CommonResult.success(pmsBrand);
            LOGGER.debug("createBrand success:{}", pmsBrand);
        } else {
            commonResult = CommonResult.failed("Operation failed");
            LOGGER.debug("createBrand failed:{}", pmsBrand);
        }
        return commonResult;
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {
        CommonResult commonResult;
        int count = demoService.updateBrand(id, pmsBrandDto);
        if (count == 1) {
            commonResult = CommonResult.success(pmsBrandDto);
            LOGGER.debug("updateBrand success:{}", pmsBrandDto);
        } else {
            commonResult = CommonResult.failed("Operation failed");
            LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
        }
        return commonResult;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult deleteBrand(@PathVariable("id") Long id) {
        int count = demoService.deleteBrand(id);
        if (count == 1) {
            LOGGER.debug("deleteBrand success :id={}", id);
            return CommonResult.success(null);
        } else {
            LOGGER.debug("deleteBrand failed :id={}", id);
            return CommonResult.failed("Operation failed"); }}@RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
        List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(brandList));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
        returnCommonResult.success(demoService.getBrand(id)); }}Copy the code

Adding a Service Interface

package com.macro.mall.tiny.service;


import com.macro.mall.tiny.mbg.model.PmsBrand;

import java.util.List;

/** * PmsBrandService * Created by macro on 2019/4/19. */
public interface PmsBrandService {
    List<PmsBrand> listAllBrand(a);

    int createBrand(PmsBrand brand);

    int updateBrand(Long id, PmsBrand brand);

    int deleteBrand(Long id);

    List<PmsBrand> listBrand(int pageNum, int pageSize);

    PmsBrand getBrand(Long id);
}

Copy the code

Implementing the Service interface

package com.macro.mall.tiny.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.tiny.mbg.mapper.PmsBrandMapper;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.mbg.model.PmsBrandExample;
import com.macro.mall.tiny.service.PmsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** * PmsBrandService implementations * Created by Macro on 2019/4/19. */
@Service
public class PmsBrandServiceImpl implements PmsBrandService {
    @Autowired
    private PmsBrandMapper brandMapper;

    @Override
    public List<PmsBrand> listAllBrand(a) {
        return brandMapper.selectByExample(new PmsBrandExample());
    }

    @Override
    public int createBrand(PmsBrand brand) {
        return brandMapper.insertSelective(brand);
    }

    @Override
    public int updateBrand(Long id, PmsBrand brand) {
        brand.setId(id);
        return brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public int deleteBrand(Long id) {
        return brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<PmsBrand> listBrand(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return brandMapper.selectByExample(new PmsBrandExample());
    }

    @Override
    public PmsBrand getBrand(Long id) {
        returnbrandMapper.selectByPrimaryKey(id); }}Copy the code

Project source address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, pay attention to the public account for the first time.