商城项目(一)使用Spring boot + Mybatis搭建
Spring boot + Mybatis基础架构
环境搭建
- mysql 8
- mysql客户端连接工具 Valentina Studio
- springboot 版本:2.1.3.RELEASE
- Mybatis
- PagerHelper(Mybatis分页插件)
- Druid数据库连接池
- Mybatis generator
项目搭建
使用IDEA初始化一个SpringBoot项目
添加项目依赖(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>
修改SpringBoot配置文件
在application.yml中添加数据源配置和MyBatis的mapper.xml的路径配置。
server:port: 8080spring:datasource:url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: nez123456mybatis:mapper-locations:- classpath:mapper/*.xml- classpath*:com/**/mapper/*.xml
项目结构
Mybatis generator 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//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>
运行Generator的main函数生成代码
/*** 用于生产MBG的代码*/
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);//创建 MBGMyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);//执行生成代码myBatisGenerator.generate(null);//输出警告信息for (String warning : warnings) {System.out.println(warning);}}
}
添加MyBatis的Java配置
用于配置需要动态生成的mapper接口的路径
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;/*** MyBatis配置类*/
@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {}
实现Controller中的接口
实现PmsBrand表中的添加、修改、删除及分页查询接口。
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*/
@Controller
@RequestMapping("/brand")
public class PmsBrandController {@Autowiredprivate PmsBrandService demoService;private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);@RequestMapping(value = "listAll", method = RequestMethod.GET)@ResponseBodypublic CommonResult<List<PmsBrand>> getBrandList() {return CommonResult.success(demoService.listAllBrand());}@RequestMapping(value = "/create", method = RequestMethod.POST)@ResponseBodypublic 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)@ResponseBodypublic 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)@ResponseBodypublic 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)@ResponseBodypublic 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)@ResponseBodypublic CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {return CommonResult.success(demoService.getBrand(id));}
}
添加Service接口及实现
import com.macro.mall.tiny.mbg.model.PmsBrand;import java.util.List;/*** PmsBrandService* Created by macro on 2019/4/19.*/
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);
}
import com.github.pagehelper.PageHelper;
import com.macro.mall.tiny.mbg.mapper.PmsBrandMapper;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.mbg.model.PmsBrandExample;
import com.macro.mall.tiny.service.PmsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** PmsBrandService实现类* Created by macro on 2019/4/19.*/
@Service
public class PmsBrandServiceImpl implements PmsBrandService {@Autowiredprivate PmsBrandMapper brandMapper;@Overridepublic List<PmsBrand> listAllBrand() {return brandMapper.selectByExample(new PmsBrandExample());}@Overridepublic int createBrand(PmsBrand brand) {return brandMapper.insertSelective(brand);}@Overridepublic int updateBrand(Long id, PmsBrand brand) {brand.setId(id);return brandMapper.updateByPrimaryKeySelective(brand);}@Overridepublic int deleteBrand(Long id) {return brandMapper.deleteByPrimaryKey(id);}@Overridepublic List<PmsBrand> listBrand(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);return brandMapper.selectByExample(new PmsBrandExample());}@Overridepublic PmsBrand getBrand(Long id) {return brandMapper.selectByPrimaryKey(id);}
}
商城项目(一)使用Spring boot + Mybatis搭建相关推荐
- java多模块项目脚手架:Spring Boot + MyBatis 搭建教程
作者 | 枫本非凡 链接 | cnblogs.com/orzlin/p/9717399.html 一.前言 最近公司项目准备开始重构,框架选定为SpringBoot+Mybatis,本篇主要记录了在I ...
- 从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建
从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建 本文简介 为什么使用Spring Boot 搭建怎样一个环境 开发环境 导入快速启动 ...
- spring boot+mybatis框架环境搭建
配置spring boot+mybatis框架环境搭建 一, spring boot 环境搭建 以下步骤为 1,新建maven工程 2.在pom文件中添加: spring-boot-starter-p ...
- 【Spring Boot】使用Spring Boot来搭建Java web项目以及开发过程
[Spring Boot]使用Spring Boot来搭建Java web项目以及开发过程 一.Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来 ...
- Eclipse + Spring boot +mybatis + mysql
Eclipse + Spring boot +mybatis + mysql 如题.使用Springboot 2.0 版本进行网页的开发.原理和优点很多博文已经讲过了,这里不再赘述.但是很多项目按照他 ...
- spring boot+mybatis整合
LZ今天自己搭建了下Spring boot+Mybatis,比原来的Spring+SpringMVC+Mybatis简单好多.其实只用Spring boot也可以开发,但是对于多表多条件分页查询,Sp ...
- Spring boot Mybatis 整合(注解版)
之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...
- Spring Boot + Mybatis 快速整合
引言 最近在工作结束后抽时间学习了一下mybatis的知识,因为之前有学习过,但是经久不用,也未曾踏实地整理,因此有所淡忘. super meeting会议管理系统是我厂最近开发的一套会议预约平台.持 ...
- Spring boot Mybatis 整合(完整版)
Spring boot Mybatis 整合(完整版) 更多干货 SpringBoot系列目录 正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: ...
最新文章
- 统计学派的18种经典「数据分析方法」
- CTOR在区块熵编码中的优点
- vim win装_VIM的代码补全工具YouCompleteMe在Windows上的安装攻略
- 文件/目录权限相关命令:chmod、chown、umask、lsattr/chattr命令解析
- python谱聚类算法_谱聚类(spectral clustering)原理总结
- 外圆内方与外方内圆的奇妙变换!
- android插件化-获取apkplug框架已安装插件-03
- 我的程序跑了 60 多小时,就是为了让你看一眼 JDK 的 BUG 导致的内存泄漏
- Thrift介绍与应用(三)—hbase的thrift接口
- python数据分析模块包括_数据开发必会 | Python数据分析模块
- 递归函数合式分解python_学习python的day10之递归与内置函数
- 转:OWASP发布Web应用程序的十大安全风险
- 怎么手动升级更新ubuntu系统到最新版
- 7-9 字符串字母大小写转换 (15 point(s))
- 超级计算机运存多少,6GB内存到底能开多少个APP?实测告诉你最终答案
- 还在考驾照的你知道汽车是怎么动起来的吗?
- 神州信息郭为:以《数字化的力量》为锚,驶向数字文明的星辰大海
- Django! 褪去浮华
- 高级软件工程师和架构师的区别
- 一款好用的文本编辑器KindEditor+PHP