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

mysql数据库环境搭建

项目使用框架介绍

SpringBoot

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

PagerHelper

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

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

Druid

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

Mybatis generator

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

项目搭建

使用IDEA初始化一个SpringBoot项目

mall整合SpringBoot MyBatis搭建基本骨架 - 图1

添加项目依赖

在pom.xml中添加相关依赖。

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.3.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencies>
  8. <!--SpringBoot通用依赖模块-->
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-actuator</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-aop</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. <!--MyBatis分页插件-->
  27. <dependency>
  28. <groupId>com.github.pagehelper</groupId>
  29. <artifactId>pagehelper-spring-boot-starter</artifactId>
  30. <version>1.2.10</version>
  31. </dependency>
  32. <!--集成druid连接池-->
  33. <dependency>
  34. <groupId>com.alibaba</groupId>
  35. <artifactId>druid-spring-boot-starter</artifactId>
  36. <version>1.1.10</version>
  37. </dependency>
  38. <!-- MyBatis 生成器 -->
  39. <dependency>
  40. <groupId>org.mybatis.generator</groupId>
  41. <artifactId>mybatis-generator-core</artifactId>
  42. <version>1.3.3</version>
  43. </dependency>
  44. <!--Mysql数据库驱动-->
  45. <dependency>
  46. <groupId>mysql</groupId>
  47. <artifactId>mysql-connector-java</artifactId>
  48. <version>8.0.15</version>
  49. </dependency>
  50. </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

项目结构说明

mall整合SpringBoot MyBatis搭建基本骨架 - 图2

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. return brandMapper.selectByExample(new PmsBrandExample());
  39. }
  40. @Override
  41. public PmsBrand getBrand(Long id) {
  42. return brandMapper.selectByPrimaryKey(id);
  43. }
  44. }

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-01