学习不走弯路,通过《mall视频教程(最新版)》,使用更系统、高效的方式来学习mall电商实战项目吧!
mall整合SpringBoot+MyBatis搭建基本框架
mall整合SpringBoot+MyBatis搭建基本框架
在前面的课程中我们学习了SpringBoot和MyBatis的使用,这一节我们就正式开始搭建项目脚手架
mall-tiny
了,本节主要讲解整合SpringBoot+MyBatis搭建基本框架,以商品品牌为例实现基本的CRUD操作。
相关视频教程
mall整合SpringBoot+MyBatis搭建基本框架
前置知识
在搭建框架之前,我们需要对mall项目使用的技术有一定了解,这一节我们需要SpringBoot、MyBatis、MyBatis Generator、Lombok和Hutool的知识,具体参考以下课程。
MySql数据库环境搭建
- 下载并安装mysql5.7版本,下载地址:https://dev.mysql.com/downloads/installer/
- 设置数据库帐号密码
root:root
; - 下载并安装客户端连接工具Navicat,下载地址:http://www.formysql.com/xiazai.html
- 创建数据库
mall_tiny
; - 导入mall_tiny的数据库脚本,脚本地址:https://github.com/macrozheng/mall-learning/blob/teach/document/sql/mall_tiny.sql
项目搭建
- 使用IDEA初始化一个SpringBoot项目;
- 在
pom.xml
文件中添加相关依赖;
<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>${pagehelper-starter.version}</version>
</dependency>
<!--集成druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis-generator.version}</version>
</dependency>
<!--Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
</dependency>
<!--Lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--Hutool工具类库-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
</dependencies>
- 在配置文件
application.yml
中添加数据源配置和MyBatis的mapper.xml
文件路径配置,自定义的mapper.xml
文件我们将放在dao
目录下;
在application.yml中添加数据源配置和MyBatis的mapper.xml的路径配置。
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mall_tiny?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis:
mapper-locations:
- classpath:dao/*.xml
- classpath*:com/**/mapper/*.xml
- 项目最终目录结构如下;
- 创建MBG的数据库配置文件
generator.properties
,内容如下;
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/mall_tiny?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.userId=root
jdbc.password=root
- 创建MBG的代码生成器配置
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">
<!-- 配置SQL语句中的前置分隔符 -->
<property name="beginningDelimiter" value="`"/>
<!-- 配置SQL语句中的后置分隔符 -->
<property name="endingDelimiter" value="`"/>
<!-- 配置生成Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!--生成mapper.xml时覆盖原文件-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
<!-- 为模型生成序列化方法-->
<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">
<!-- 是否阻止生成的注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 是否阻止生成的注释包含时间戳 -->
<property name="suppressDate" value="true"/>
<!-- 是否添加数据库表的备注信息 -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- 配置MBG要连接的数据库信息 -->
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
<!-- 解决mysql驱动升级到8.0后不生成指定数据库代码的问题 -->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<!-- 用于控制实体类的生成 -->
<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>
- 运行Generator类的main方法生成代码;
/**
* @auther macrozheng
* @description 用于生产MBG的代码
* @date 2018/4/26
* @github https://github.com/macrozheng
*/
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);
}
}
}
- 添加MyBatis的Java配置,用于配置需要动态生成的Mapper接口的路径;
添加MyBatis的Java配置
用于配置需要动态生成的mapper接口的路径
/**
* @auther macrozheng
* @description MyBatis配置类
* @date 2019/4/8
* @github https://github.com/macrozheng
*/
@Configuration
@MapperScan({"com.macro.mall.tiny.mbg.mapper","com.macro.mall.tiny.dao"})
public class MyBatisConfig {
}
- 在controller层定义好接口,实现商品品牌表中的添加、修改、删除及分页查询接口;
实现Controller中的接口
实现PmsBrand表中的添加、修改、删除及分页查询接口。
/**
* @auther macrozheng
* @description 品牌管理Controller
* @date 2019/4/19
* @github https://github.com/macrozheng
*/
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@RequestMapping(value = "/listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
CommonResult commonResult;
int count = brandService.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 = brandService.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 = brandService.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 = brandService.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(brandService.getBrand(id));
}
}
- 在service层中添加业务接口;
/**
* @auther macrozheng
* @description PmsBrandService
* @date 2019/4/19
* @github https://github.com/macrozheng
*/
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);
}
- 实现service层中的业务接口。
/**
* @auther macrozheng
* @description PmsBrandService实现类
* @date 2019/4/19
* @github https://github.com/macrozheng
*/
@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);
}
}
项目源码地址
https://github.com/macrozheng/mall-learning/tree/teach/mall-tiny-01