本文主要讲解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌为例实现基本的CRUD操作及通过PageHelper实现分页查询。
SpringBoot可以让你快速构建基于Spring的Web应用程序,内置多种Web容器(如Tomcat),通过启动入口程序的main函数即可运行。
MyBatis分页插件,简单的几行代码就能实现分页,在与SpringBoot整合时,只要整合了PagerHelper就自动整合了MyBatis。
PageHelper.startPage(pageNum, pageSize); //之后进行查询操作将自动进行分页 List<PmsBrand> brandList = brandMapper.selectByExample(new PmsBrandExample()); //通过构造PageInfo对象获取分页信息,如当前页码,总页数,总条数 PageInfo<PmsBrand> pageInfo = new PageInfo<PmsBrand>(list);alibaba开源的数据库连接池,号称Java语言中最好的数据库连接池。
MyBatis的代码生成器,可以根据数据库生成model、mapper.xml、mapper接口和Example,通常情况下的单表查询不用再手写mapper。
在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>在application.yml中添加数据源配置和MyBatis的mapper.xml的路径配置。
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配置数据库连接,Mybatis generator生成model、mapper接口及mapper.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.macro.mall.tiny.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.macro.mall.tiny.mbg.model" targetProject="mall-tiny-01\src\main\java"/> <!--指定生成mapper.xml的路径--> <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-01\src\main\resources"/> <!--指定生成mapper接口的的路径--> <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>用于配置需要动态生成的mapper接口的路径
package com.macro.mall.tiny.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * MyBatis配置类 * Created by macro on 2019/4/8. */ @Configuration @MapperScan("com.macro.mall.tiny.mbg.mapper") public class MyBatisConfig { }实现PmsBrand表中的添加、修改、删除及分页查询接口。
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; /** * 品牌管理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("操作失败"); 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)); } }https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-01