mall整合SpringBoot+MyBatis搭建基本骨架

本文主要讲解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌为例实现基本的CRUD操作及通过PageHelper实现分页查询。

mysql数据库环境搭建

  • 下载并安装mysql5.7版本,下载地址:https://dev.mysql.com/downloads/installer/

  • 设置数据库帐号密码:root root

  • 下载并安装客户端连接工具Navicat,下载地址:http://www.formysql.com/xiazai.html

  • 创建数据库mall

  • 导入mall的数据库脚本,脚本地址:https://github.com/macrozheng/mall-learning/blob/master/document/sql/mall.sql

项目使用框架介绍

SpringBoot

SpringBoot可以让你快速构建基于Spring的Web应用程序,内置多种Web容器(如Tomcat),通过启动入口程序的main函数即可运行。

PagerHelper

MyBatis分页插件,简单的几行代码就能实现分页,在与SpringBoot整合时,只要整合了PagerHelper就自动整合了MyBatis。

PageHelper.startPage(pageNum, pageSize);//之后进行查询操作将自动进行分页List<PmsBrand> brandList = brandMapper.selectByExample(new PmsBrandExample());//通过构造PageInfo对象获取分页信息,如当前页码,总页数,总条数PageInfo<PmsBrand> pageInfo = new PageInfo<PmsBrand>(list);

Druid

alibaba开源的数据库连接池,号称Java语言中最好的数据库连接池。

Mybatis generator

MyBatis的代码生成器,可以根据数据库生成model、mapper.xml、mapper接口和Example,通常情况下的单表查询不用再手写mapper。

项目搭建

使用IDEA初始化一个SpringBoot项目

添加项目依赖

在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通用依赖模块-->        <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分页插件-->        <dependency>            <groupId>com.github.pagehelper</groupId>            <artifactId>pagehelper-spring-boot-starter</artifactId>            <version>1.2.10</version>        </dependency>        <!--集成druid连接池-->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid-spring-boot-starter</artifactId>            <version>1.1.10</version>        </dependency>        <!-- MyBatis 生成器 -->        <dependency>            <groupId>org.mybatis.generator</groupId>            <artifactId>mybatis-generator-core</artifactId>            <version>1.3.3</version>        </dependency>        <!--Mysql数据库驱动-->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>8.0.15</version>        </dependency>    </dependencies>

修改SpringBoot配置文件

在application.yml中添加数据源配置和MyBatis的mapper.xml的路径配置。


  1. server:

  2.  port: 8080


  3. spring:

  4.  datasource:

  5.    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

  6.    username: root

  7.    password: root


  8. mybatis:

  9.  mapper-locations:

  10.    - classpath:mapper/*.xml

  11.    - classpath*:com/**/mapper/*.xml

项目结构说明

Mybatis generator 配置文件

配置数据库连接,Mybatis generator生成model、mapper接口及mapper.xml的路径。


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

  2. <!DOCTYPE generatorConfiguration

  3.        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

  4.        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


  5. <generatorConfiguration>

  6.    <properties resource="generator.properties"/>

  7.    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">

  8.        <property name="beginningDelimiter" value="`"/>

  9.        <property name="endingDelimiter" value="`"/>

  10.        <property name="javaFileEncoding" value="UTF-8"/>

  11.        <!-- 为模型生成序列化方法-->

  12.        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

  13.        <!-- 为生成的Java模型创建一个toString方法 -->

  14.        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

  15.        <!--可以自定义生成model的代码注释-->

  16.        <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">

  17.            <!-- 是否去除自动生成的注释 true:是 : false:否 -->

  18.            <property name="suppressAllComments" value="true"/>

  19.            <property name="suppressDate" value="true"/>

  20.            <property name="addRemarkComments" value="true"/>

  21.        </commentGenerator>

  22.        <!--配置数据库连接-->

  23.        <jdbcConnection driverClass="${jdbc.driverClass}"

  24.                        connectionURL="${jdbc.connectionURL}"

  25.                        userId="${jdbc.userId}"

  26.                        password="${jdbc.password}">

  27.            <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->

  28.            <property name="nullCatalogMeansCurrent" value="true" />

  29.        </jdbcConnection>

  30.        <!--指定生成model的路径-->

  31.        <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-01\src\main\java"/>

  32.        <!--指定生成mapper.xml的路径-->

  33.        <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-01\src\main\resources"/>

  34.        <!--指定生成mapper接口的的路径-->

  35.        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"

  36.                             targetProject="mall-tiny-01\src\main\java"/>

  37.        <!--生成全部表tableName设为%-->

  38.        <table tableName="pms_brand">

  39.            <generatedKey column="id" sqlStatement="MySql" identity="true"/>

  40.        </table>

  41.    </context>

  42. </generatorConfiguration>

运行Generator的main函数生成代码


  1. package com.macro.mall.tiny.mbg;


  2. import org.mybatis.generator.api.MyBatisGenerator;

  3. import org.mybatis.generator.config.Configuration;

  4. import org.mybatis.generator.config.xml.ConfigurationParser;

  5. import org.mybatis.generator.internal.DefaultShellCallback;


  6. import java.io.InputStream;

  7. import java.util.ArrayList;

  8. import java.util.List;


  9. /**

  10. * 用于生产MBG的代码

  11. * Created by macro on 2018/4/26.

  12. */

  13. public class Generator {

  14.    public static void main(String[] args) throws Exception {

  15.        //MBG 执行过程中的警告信息

  16.        List<String> warnings = new ArrayList<String>();

  17.        //当生成的代码重复时,覆盖原代码

  18.        boolean overwrite = true;

  19.        //读取我们的 MBG 配置文件

  20.        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");

  21.        ConfigurationParser cp = new ConfigurationParser(warnings);

  22.        Configuration config = cp.parseConfiguration(is);

  23.        is.close();


  24.        DefaultShellCallback callback = new DefaultShellCallback(overwrite);

  25.        //创建 MBG

  26.        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);

  27.        //执行生成代码

  28.        myBatisGenerator.generate(null);

  29.        //输出警告信息

  30.        for (String warning : warnings) {

  31.            System.out.println(warning);

  32.        }

  33.    }

  34. }

添加MyBatis的Java配置

用于配置需要动态生成的mapper接口的路径


  1. package com.macro.mall.tiny.config;


  2. import org.mybatis.spring.annotation.MapperScan;

  3. import org.springframework.context.annotation.Configuration;


  4. /**

  5. * MyBatis配置类

  6. * Created by macro on 2019/4/8.

  7. */

  8. @Configuration

  9. @MapperScan("com.macro.mall.tiny.mbg.mapper")

  10. public class MyBatisConfig {

  11. }

实现Controller中的接口

实现PmsBrand表中的添加、修改、删除及分页查询接口。


  1. package com.macro.mall.tiny.controller;


  2. import com.macro.mall.tiny.common.api.CommonPage;

  3. import com.macro.mall.tiny.common.api.CommonResult;

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

  5. import com.macro.mall.tiny.service.PmsBrandService;

  6. import org.slf4j.Logger;

  7. import org.slf4j.LoggerFactory;

  8. import org.springframework.beans.factory.annotation.Autowired;

  9. import org.springframework.stereotype.Controller;

  10. import org.springframework.validation.BindingResult;

  11. import org.springframework.web.bind.annotation.*;


  12. import java.util.List;



  13. /**

  14. * 品牌管理Controller

  15. * Created by macro on 2019/4/19.

  16. */

  17. @Controller

  18. @RequestMapping("/brand")

  19. public class PmsBrandController {

  20.    @Autowired

  21.    private PmsBrandService demoService;


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


  23.    @RequestMapping(value = "listAll", method = RequestMethod.GET)

  24.    @ResponseBody

  25.    public CommonResult<List<PmsBrand>> getBrandList() {

  26.        return CommonResult.success(demoService.listAllBrand());

  27.    }


  28.    @RequestMapping(value = "/create", method = RequestMethod.POST)

  29.    @ResponseBody

  30.    public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {

  31.        CommonResult commonResult;

  32.        int count = demoService.createBrand(pmsBrand);

  33.        if (count == 1) {

  34.            commonResult = CommonResult.success(pmsBrand);

  35.            LOGGER.debug("createBrand success:{}", pmsBrand);

  36.        } else {

  37.            commonResult = CommonResult.failed("操作失败");

  38.            LOGGER.debug("createBrand failed:{}", pmsBrand);

  39.        }

  40.        return commonResult;

  41.    }


  42.    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)

  43.    @ResponseBody

  44.    public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {

  45.        CommonResult commonResult;

  46.        int count = demoService.updateBrand(id, pmsBrandDto);

  47.        if (count == 1) {

  48.            commonResult = CommonResult.success(pmsBrandDto);

  49.            LOGGER.debug("updateBrand success:{}", pmsBrandDto);

  50.        } else {

  51.            commonResult = CommonResult.failed("操作失败");

  52.            LOGGER.debug("updateBrand failed:{}", pmsBrandDto);

  53.        }

  54.        return commonResult;

  55.    }


  56.    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)

  57.    @ResponseBody

  58.    public CommonResult deleteBrand(@PathVariable("id") Long id) {

  59.        int count = demoService.deleteBrand(id);

  60.        if (count == 1) {

  61.            LOGGER.debug("deleteBrand success :id={}", id);

  62.            return CommonResult.success(null);

  63.        } else {

  64.            LOGGER.debug("deleteBrand failed :id={}", id);

  65.            return CommonResult.failed("操作失败");

  66.        }

  67.    }


  68.    @RequestMapping(value = "/list", method = RequestMethod.GET)

  69.    @ResponseBody

  70.    public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,

  71.                                                        @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {

  72.        List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize);

  73.        return CommonResult.success(CommonPage.restPage(brandList));

  74.    }


  75.    @RequestMapping(value = "/{id}", method = RequestMethod.GET)

  76.    @ResponseBody

  77.    public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {

  78.        return CommonResult.success(demoService.getBrand(id));

  79.    }

  80. }

添加Service接口


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



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


  3. import java.util.List;


  4. /**

  5. * PmsBrandService

  6. * Created by macro on 2019/4/19.

  7. */

  8. public interface PmsBrandService {

  9.    List<PmsBrand> listAllBrand();


  10.    int createBrand(PmsBrand brand);


  11.    int updateBrand(Long id, PmsBrand brand);


  12.    int deleteBrand(Long id);


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


  14.    PmsBrand getBrand(Long id);

  15. }

实现Service接口


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


  2. import com.github.pagehelper.PageHelper;

  3. import com.macro.mall.tiny.mbg.mapper.PmsBrandMapper;

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

  5. import com.macro.mall.tiny.mbg.model.PmsBrandExample;

  6. import com.macro.mall.tiny.service.PmsBrandService;

  7. import org.springframework.beans.factory.annotation.Autowired;

  8. import org.springframework.stereotype.Service;


  9. import java.util.List;


  10. /**

  11. * PmsBrandService实现类

  12. * Created by macro on 2019/4/19.

  13. */

  14. @Service

  15. public class PmsBrandServiceImpl implements PmsBrandService {

  16.    @Autowired

  17.    private PmsBrandMapper brandMapper;


  18.    @Override

  19.    public List<PmsBrand> listAllBrand() {

  20.        return brandMapper.selectByExample(new PmsBrandExample());

  21.    }


  22.    @Override

  23.    public int createBrand(PmsBrand brand) {

  24.        return brandMapper.insertSelective(brand);

  25.    }


  26.    @Override

  27.    public int updateBrand(Long id, PmsBrand brand) {

  28.        brand.setId(id);

  29.        return brandMapper.updateByPrimaryKeySelective(brand);

  30.    }


  31.    @Override

  32.    public int deleteBrand(Long id) {

  33.        return brandMapper.deleteByPrimaryKey(id);

  34.    }


  35.    @Override

  36.    public List<PmsBrand> listBrand(int pageNum, int pageSize) {

  37.        PageHelper.startPage(pageNum, pageSize);

  38.        brandMapper.selectByExample(new PmsBrandExample());

  39.        return brandMapper.selectByExample(new PmsBrandExample());

  40.    }


  41.    @Override

  42.    public PmsBrand getBrand(Long id) {

  43.        return brandMapper.selectByPrimaryKey(id);

  44.    }

  45. }


上一篇:mall整合Mongodb实现文档操作


下一篇:mall整合SpringSecurity和JWT实现认证和授权(二)