springboot实战系列之集成mybatis

前言

springboot是当前业界最流行的后台框架之一,提供人们快速构建spring应用的能力。这里不对它的特性做过多的介绍,只讲实战。

环境

idea2019 jdk1.8 springboot2.1.3.RELEASE

搭建环境

  • 目录结构

    Yj0gGd.png

  • 数据库初始化脚本

    CREATE TABLE `pms_brand` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `name` varchar(64) DEFAULT NULL,
      `first_letter` varchar(8) DEFAULT NULL COMMENT '首字母',
      `sort` int(11) DEFAULT NULL,
      `factory_status` int(1) DEFAULT NULL COMMENT '是否为品牌制造商:0->不是;1->是',
      `show_status` int(1) DEFAULT NULL,
      `product_count` int(11) DEFAULT NULL COMMENT '产品数量',
      `product_comment_count` int(11) DEFAULT NULL COMMENT '产品评论数量',
      `logo` varchar(255) DEFAULT NULL COMMENT '品牌logo',
      `big_pic` varchar(255) DEFAULT NULL COMMENT '专区大图',
      `brand_story` text COMMENT '品牌故事',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8 COMMENT='品牌表';
    
  • 快速生成一个springboot工程

    初始化一个springboot主要有三种方式:

Yjs3l9.md.png

这里主要注意修改springboot的版本、maven的gav信息,项目打包方式、jdk版本以及项目的依赖
  • idea里集成start.spring.io来生成

    【File】-【New】- 【Project】-【Spirng Initializr】

    同上,配置项目相关信息,可以生成一个springboot工程。

  • 利用springboot cli命令来生成

  • 在POM文件里添加mybatis相关依赖

    <!--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>
    
  • 使用generate插件生成实体类和mapper

    1. 在resources目录下新建generator.properties和generatorConfig.xml

      generator.properties

      jdbc.driverClass=com.mysql.cj.jdbc.Driver
      jdbc.connectionURL=jdbc:mysql://172.16.15.105/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
      jdbc.userId=root
      jdbc.password=root
      

      generatorConfig.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE generatorConfiguration
              PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
              "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
      
      <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"/>
              <!-- 为模型生成序列化方法-->
              <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
              <!-- 为生成的Java模型创建一个toString方法 -->
              <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
              <!--可以自定义生成model的代码注释-->
              <commentGenerator type="com.allen.springbootdao.mbg.CommentGenerator">
                  <!-- 是否去除自动生成的注释 true:是 : false:否 -->
                  <property name="suppressAllComments" value="true"/>
                  <property name="suppressDate" value="true"/>
                  <property name="addRemarkComments" value="true"/>
              </commentGenerator>
              <!--配置数据库连接-->
              <jdbcConnection driverClass="${jdbc.driverClass}"
                              connectionURL="${jdbc.connectionURL}"
                              userId="${jdbc.userId}"
                              password="${jdbc.password}">
                  <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
                  <property name="nullCatalogMeansCurrent" value="true" />
              </jdbcConnection>
              <!--指定生成model的路径-->
              <javaModelGenerator targetPackage="com.allen.springbootdao.mbg.model" targetProject="springbootdao\src\main\java"/>
              <!--指定生成mapper.xml的路径-->
              <sqlMapGenerator targetPackage="com.allen.springbootdao.mbg.mapper" targetProject="springbootdao\src\main\resources"/>
              <!--指定生成mapper接口的的路径-->
              <javaClientGenerator type="XMLMAPPER" targetPackage="com.allen.springbootdao.mbg.mapper"
                                   targetProject="springbootdao\src\main\java"/>
              <!--生成全部表tableName设为%-->
              <table tableName="pms_brand">
                  <generatedKey column="id" sqlStatement="MySql" identity="true"/>
              </table>
          </context>
      </generatorConfiguration>
      
      
    2. 在com.allen.springbootdao.mbg下新建CommonGenerator和Generator

      CommonGenerator.java

      package com.allen.springbootdao.mbg;
      
      import org.mybatis.generator.api.IntrospectedColumn;
      import org.mybatis.generator.api.IntrospectedTable;
      import org.mybatis.generator.api.dom.java.CompilationUnit;
      import org.mybatis.generator.api.dom.java.Field;
      import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
      import org.mybatis.generator.internal.DefaultCommentGenerator;
      import org.mybatis.generator.internal.util.StringUtility;
      
      import java.util.Properties;
      
      public class CommentGenerator extends DefaultCommentGenerator {
          private boolean addRemarkComments = false;
          private static final String EXAMPLE_SUFFIX="Example";
          private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
      
          /**
           * 设置用户配置的参数
           */
          @Override
          public void addConfigurationProperties(Properties properties) {
              super.addConfigurationProperties(properties);
              this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
          }
      
          /**
           * 给字段添加注释
           */
          @Override
          public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                      IntrospectedColumn introspectedColumn) {
              String remarks = introspectedColumn.getRemarks();
              //根据参数和备注信息判断是否添加备注信息
              if(addRemarkComments&& StringUtility.stringHasValue(remarks)){
      //            addFieldJavaDoc(field, remarks);
                  //数据库中特殊字符需要转义
                  if(remarks.contains("\"")){
                      remarks = remarks.replace("\"","'");
                  }
                  //给model的字段添加swagger注解
                  field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
              }
          }
      
          /**
           * 给model的字段添加注释
           */
          private void addFieldJavaDoc(Field field, String remarks) {
              //文档注释开始
              field.addJavaDocLine("/**");
              //获取数据库字段的备注信息
              String[] remarkLines = remarks.split(System.getProperty("line.separator"));
              for(String remarkLine:remarkLines){
                  field.addJavaDocLine(" * "+remarkLine);
              }
              addJavadocTag(field, false);
              field.addJavaDocLine(" */");
          }
      
          @Override
          public void addJavaFileComment(CompilationUnit compilationUnit) {
              super.addJavaFileComment(compilationUnit);
              //只在model中添加swagger注解类的导入
              if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
                  compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
              }
          }
      }
      

      Generator.java

      package com.allen.springbootdao.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;
      
      public class Generator {
          public static void main(String[] args) throws Exception {
              //MBG 执行过程中的警告信息
              List<String> warnings = new ArrayList<String>();
              //当生成的代码重复时,覆盖原代码
              boolean overwrite = true;
              //读取我们的 MBG 配置文件
              InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
              ConfigurationParser cp = new ConfigurationParser(warnings);
              Configuration config = cp.parseConfiguration(is);
              is.close();
      
              DefaultShellCallback callback = new DefaultShellCallback(overwrite);
              //创建 MBG
              MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
              //执行生成代码
              myBatisGenerator.generate(null);
              //输出警告信息
              for (String warning : warnings) {
                  System.out.println(warning);
              }
          }
      }
      

      如果你自定义自己的报名,注意修改Generator.java里的生成包路径信息。

      建议可以把生成的xxxMapper类和实体类移到外层的dao和dto目录。这个是个人喜好。

  • 添加config类

    @Configuration
    @MapperScan("com.allen.springbootdao.mbg.mapper")
    public class MybatisConfig {
    }
    
  • 添加service和controller

    PmsBrandService

    package com.allen.springbootdao.service;
    
    
    import com.allen.springbootdao.mbg.model.PmsBrand;
    
    import java.util.List;
    
    public interface PmsBrandService {
        List<PmsBrand> listAllBrand();
    
        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);
    }
    
    

    PmsBrandServiceImpl

    @Service
    public class PmsBrandServiceImpl implements PmsBrandService {
        @Autowired
        private PmsBrandMapper brandMapper;
    
        @Override
        public List<PmsBrand> listAllBrand() {
            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) {
            return brandMapper.selectByPrimaryKey(id);
        }
    }
    
    

    PmsBrandController

    @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("操作失败");
                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("操作失败");
                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("操作失败");
            }
        }
    
        @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) {
            return CommonResult.success(demoService.getBrand(id));
        }
    }
    
    

至此,项目搭建完成,可以运行项目验证下是否搭建成功。

小结

有了springboot,构建一个spring是一件很容易的事情,而且你发现,我们的应用基本上没用到xml配置,甚至可以完全不需要xml。

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读