本文主要講解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌為例實(shí)現(xiàn)基本的CRUD操作及通過(guò)PageHelper實(shí)現(xiàn)分頁(yè)查詢薇正。
mysql數(shù)據(jù)庫(kù)環(huán)境搭建
下載并安裝mysql5.7版本巩剖,下載地址:https://dev.mysql.com/downloads/installer/
設(shè)置數(shù)據(jù)庫(kù)帳號(hào)密碼:root root
下載并安裝客戶端連接工具Navicat,下載地址:http://www.formysql.com/xiazai.html
創(chuàng)建數(shù)據(jù)庫(kù)mall
導(dǎo)入mall的數(shù)據(jù)庫(kù)腳本,腳本地址:https://github.com/macrozheng/mall-learning/blob/master/document/sql/mall.sql
SpringBoot可以讓你快速構(gòu)建基于Spring的Web應(yīng)用程序佳魔,內(nèi)置多種Web容器(如Tomcat),通過(guò)啟動(dòng)入口程序的main函數(shù)即可運(yùn)行鞠鲜。
MyBatis分頁(yè)插件宁脊,簡(jiǎn)單的幾行代碼就能實(shí)現(xiàn)分頁(yè),在與SpringBoot整合時(shí)贤姆,只要整合了PagerHelper就自動(dòng)整合了MyBatis榆苞。
PageHelper.startPage(pageNum,pageSize);//之后進(jìn)行查詢操作將自動(dòng)進(jìn)行分頁(yè)List<PmsBrand>brandList=brandMapper.selectByExample(newPmsBrandExample());//通過(guò)構(gòu)造PageInfo對(duì)象獲取分頁(yè)信息,如當(dāng)前頁(yè)碼霞捡,總頁(yè)數(shù)坐漏,總條數(shù)PageInfo<PmsBrand>pageInfo=newPageInfo<PmsBrand>(list);Copy to clipboardErrorCopied
alibaba開(kāi)源的數(shù)據(jù)庫(kù)連接池,號(hào)稱Java語(yǔ)言中最好的數(shù)據(jù)庫(kù)連接池碧信。
MyBatis的代碼生成器赊琳,可以根據(jù)數(shù)據(jù)庫(kù)生成model、mapper.xml砰碴、mapper接口和Example躏筏,通常情況下的單表查詢不用再手寫mapper。
使用IDEA初始化一個(gè)SpringBoot項(xiàng)目
在pom.xml中添加相關(guān)依賴呈枉。
<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分頁(yè)插件--><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數(shù)據(jù)庫(kù)驅(qū)動(dòng)--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version></dependency></dependencies>Copy to clipboardErrorCopied
在application.yml中添加數(shù)據(jù)源配置和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/*.xmlCopy to clipboardErrorCopied
配置數(shù)據(jù)庫(kù)連接埃碱,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><propertiesresource="generator.properties"/><contextid="MySqlContext"targetRuntime="MyBatis3"defaultModelType="flat"><propertyname="beginningDelimiter"value="`"/><propertyname="endingDelimiter"value="`"/><propertyname="javaFileEncoding"value="UTF-8"/><!-- 為模型生成序列化方法--><plugintype="org.mybatis.generator.plugins.SerializablePlugin"/><!-- 為生成的Java模型創(chuàng)建一個(gè)toString方法 --><plugintype="org.mybatis.generator.plugins.ToStringPlugin"/><!--可以自定義生成model的代碼注釋--><commentGeneratortype="com.macro.mall.tiny.mbg.CommentGenerator"><!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 --><propertyname="suppressAllComments"value="true"/><propertyname="suppressDate"value="true"/><propertyname="addRemarkComments"value="true"/></commentGenerator><!--配置數(shù)據(jù)庫(kù)連接--><jdbcConnectiondriverClass="${jdbc.driverClass}"connectionURL="${jdbc.connectionURL}"userId="${jdbc.userId}"password="${jdbc.password}"><!--解決mysql驅(qū)動(dòng)升級(jí)到8.0后不生成指定數(shù)據(jù)庫(kù)代碼的問(wèn)題--><propertyname="nullCatalogMeansCurrent"value="true"/></jdbcConnection><!--指定生成model的路徑--><javaModelGeneratortargetPackage="com.macro.mall.tiny.mbg.model"targetProject="mall-tiny-01\src\main\java"/><!--指定生成mapper.xml的路徑--><sqlMapGeneratortargetPackage="com.macro.mall.tiny.mbg.mapper"targetProject="mall-tiny-01\src\main\resources"/><!--指定生成mapper接口的的路徑--><javaClientGeneratortype="XMLMAPPER"targetPackage="com.macro.mall.tiny.mbg.mapper"targetProject="mall-tiny-01\src\main\java"/><!--生成全部表tableName設(shè)為%--><tabletableName="pms_brand"><generatedKeycolumn="id"sqlStatement="MySql"identity="true"/></table></context></generatorConfiguration>Copy to clipboardErrorCopied
運(yùn)行Generator的main函數(shù)生成代碼
packagecom.macro.mall.tiny.mbg;importorg.mybatis.generator.api.MyBatisGenerator;importorg.mybatis.generator.config.Configuration;importorg.mybatis.generator.config.xml.ConfigurationParser;importorg.mybatis.generator.internal.DefaultShellCallback;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.List;/**
* 用于生產(chǎn)MBG的代碼
* Created by macro on 2018/4/26.
*/publicclassGenerator{publicstaticvoidmain(String[]args)throwsException{//MBG 執(zhí)行過(guò)程中的警告信息List<String>warnings=newArrayList<String>();//當(dāng)生成的代碼重復(fù)時(shí)砚殿,覆蓋原代碼booleanoverwrite=true;//讀取我們的 MBG 配置文件InputStreamis=Generator.class.getResourceAsStream("/generatorConfig.xml");ConfigurationParsercp=newConfigurationParser(warnings);Configurationconfig=cp.parseConfiguration(is);is.close();DefaultShellCallbackcallback=newDefaultShellCallback(overwrite);//創(chuàng)建 MBGMyBatisGeneratormyBatisGenerator=newMyBatisGenerator(config,callback,warnings);//執(zhí)行生成代碼myBatisGenerator.generate(null);//輸出警告信息for(Stringwarning:warnings){System.out.println(warning);}}}Copy to clipboardErrorCopied
用于配置需要?jiǎng)討B(tài)生成的mapper接口的路徑
packagecom.macro.mall.tiny.config;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.context.annotation.Configuration;/**
* MyBatis配置類
* Created by macro on 2019/4/8.
*/@Configuration@MapperScan("com.macro.mall.tiny.mbg.mapper")publicclassMyBatisConfig{}Copy to clipboardErrorCopied
實(shí)現(xiàn)PmsBrand表中的添加、修改婶博、刪除及分頁(yè)查詢接口瓮具。
packagecom.macro.mall.tiny.controller;importcom.macro.mall.tiny.common.api.CommonPage;importcom.macro.mall.tiny.common.api.CommonResult;importcom.macro.mall.tiny.mbg.model.PmsBrand;importcom.macro.mall.tiny.service.PmsBrandService;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.validation.BindingResult;importorg.springframework.web.bind.annotation.*;importjava.util.List;/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/@Controller@RequestMapping("/brand")publicclassPmsBrandController{@AutowiredprivatePmsBrandServicedemoService;privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(PmsBrandController.class);@RequestMapping(value="listAll",method=RequestMethod.GET)@ResponseBodypublicCommonResult<List<PmsBrand>>getBrandList(){returnCommonResult.success(demoService.listAllBrand());}@RequestMapping(value="/create",method=RequestMethod.POST)@ResponseBodypublicCommonResultcreateBrand(@RequestBodyPmsBrandpmsBrand){CommonResultcommonResult;intcount=demoService.createBrand(pmsBrand);if(count==1){commonResult=CommonResult.success(pmsBrand);LOGGER.debug("createBrand success:{}",pmsBrand);}else{commonResult=CommonResult.failed("操作失敗");LOGGER.debug("createBrand failed:{}",pmsBrand);}returncommonResult;}@RequestMapping(value="/update/{id}",method=RequestMethod.POST)@ResponseBodypublicCommonResultupdateBrand(@PathVariable("id")Longid,@RequestBodyPmsBrandpmsBrandDto,BindingResultresult){CommonResultcommonResult;intcount=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);}returncommonResult;}@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)@ResponseBodypublicCommonResultdeleteBrand(@PathVariable("id")Longid){intcount=demoService.deleteBrand(id);if(count==1){LOGGER.debug("deleteBrand success :id={}",id);returnCommonResult.success(null);}else{LOGGER.debug("deleteBrand failed :id={}",id);returnCommonResult.failed("操作失敗");}}@RequestMapping(value="/list",method=RequestMethod.GET)@ResponseBodypublicCommonResult<CommonPage<PmsBrand>>listBrand(@RequestParam(value="pageNum",defaultValue="1")IntegerpageNum,@RequestParam(value="pageSize",defaultValue="3")IntegerpageSize){List<PmsBrand>brandList=demoService.listBrand(pageNum,pageSize);returnCommonResult.success(CommonPage.restPage(brandList));}@RequestMapping(value="/{id}",method=RequestMethod.GET)@ResponseBodypublicCommonResult<PmsBrand>brand(@PathVariable("id")Longid){returnCommonResult.success(demoService.getBrand(id));}}Copy to clipboardErrorCopied
packagecom.macro.mall.tiny.service;importcom.macro.mall.tiny.mbg.model.PmsBrand;importjava.util.List;/**
* PmsBrandService
* Created by macro on 2019/4/19.
*/publicinterfacePmsBrandService{List<PmsBrand>listAllBrand();intcreateBrand(PmsBrandbrand);intupdateBrand(Longid,PmsBrandbrand);intdeleteBrand(Longid);List<PmsBrand>listBrand(intpageNum,intpageSize);PmsBrandgetBrand(Longid);}Copy to clipboardErrorCopied
packagecom.macro.mall.tiny.service.impl;importcom.github.pagehelper.PageHelper;importcom.macro.mall.tiny.mbg.mapper.PmsBrandMapper;importcom.macro.mall.tiny.mbg.model.PmsBrand;importcom.macro.mall.tiny.mbg.model.PmsBrandExample;importcom.macro.mall.tiny.service.PmsBrandService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.List;/**
* PmsBrandService實(shí)現(xiàn)類
* Created by macro on 2019/4/19.
*/@ServicepublicclassPmsBrandServiceImplimplementsPmsBrandService{@AutowiredprivatePmsBrandMapperbrandMapper;@OverridepublicList<PmsBrand>listAllBrand(){returnbrandMapper.selectByExample(newPmsBrandExample());}@OverridepublicintcreateBrand(PmsBrandbrand){returnbrandMapper.insertSelective(brand);}@OverridepublicintupdateBrand(Longid,PmsBrandbrand){brand.setId(id);returnbrandMapper.updateByPrimaryKeySelective(brand);}@OverridepublicintdeleteBrand(Longid){returnbrandMapper.deleteByPrimaryKey(id);}@OverridepublicList<PmsBrand>listBrand(intpageNum,intpageSize){PageHelper.startPage(pageNum,pageSize);returnbrandMapper.selectByExample(newPmsBrandExample());}@OverridepublicPmsBrandgetBrand(Longid){returnbrandMapper.selectByPrimaryKey(id);}}