day01 微信商城后台管理系统框架搭建 | CRUD实现 | MP代码生成器 | Swagger2在线文档
创建项目
项目名含大写字母会报异常
啥都不选
之后点完成
根项目的pom依赖如下,部分依赖可能用不到,这个后期再做处理
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dd</groupId>
<artifactId>wechatstore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wechatstore</name>
<description>weChatStore</description>
<properties>
<skipTests>true</skipTests>
<java.version>1.8</java.version>
<cloud.version>Hoxton.RELEASE</cloud.version>
<alibaba.version>2.2.0.RELEASE</alibaba.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
<mysql.version>5.1.46</mysql.version>
<swagger.version>2.9.2</swagger.version>
<jwt.version>0.7.0</jwt.version>
<fastjson.version>1.2.29</fastjson.version>
<httpclient.version>4.5.1</httpclient.version>
<easyexcel.version>2.2.0-beta2</easyexcel.version>
<aliyun.version>4.5.14</aliyun.version>
<jodatime.version>2.10.1</jodatime.version>
<jwt.version>0.7.0</jwt.version>
<xxl-job.version>2.3.0</xxl-job.version>
<aliyun.oss.version>3.9.0</aliyun.oss.version>
</properties>
<!--配置dependencyManagement锁定依赖的版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun.version}</version>
</dependency>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>${xxl-job.version}</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
删掉src目录,因为这里我们选择多模块
新建一个module(展示一次,后续新建模块不做截图)
之后点完成即可
model里面我们放一些公共的实体类
pom.xml里对呀的依赖如下
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven中央仓库搜索2.X最新版本号-->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<scope>provided </scope>
</dependency>
<!--创建索引库的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
创建一个BaseEntity内容如下:
package com.dd.wechatstore.model.base;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Data
public class BaseEntity implements Serializable {
@ApiModelProperty(value = "id")
@TableId(type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField("create_time")
private Date createTime;
@ApiModelProperty(value = "更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField("update_time")
private Date updateTime;
@ApiModelProperty(value = "逻辑删除(1:已删除,0:未删除)")
@JsonIgnore
@TableLogic
@TableField("is_deleted")
private Integer isDeleted;
@ApiModelProperty(value = "其他参数")
@TableField(exist = false)
private Map<String,Object> param = new HashMap<>();
}
介绍一下id是每个表的主键
createTime是每条记录的创建时间
updateTime是每条记录的更新时间
isDeleted是假删除用的,因为商城项目暂时所有记录都要假删除,以免出现问题排查不了
param暂时不用,后面再说
然后我们建一下对应的mysql表
目前是前期的准备工作,所以数据库还没定,我就自己虚拟机上搞一下mysql
顺便提一下,用docker安装一个mysql是挺方便的,可以看我之前的博客
linux docker 极速安装 mysql | 设置开机自启 | 详细教程
建一个测试库
以客户表为例
注:unsigned属性就是将数字类型无符号化,例如INT的类型范围是-2 147 483 648 ~ 2 147 483 647, INT UNSIGNED的范围类型就是0 ~ 4 294 967 295。可以增加字段长度
初步需求里还有一个购买量的内容,我觉得应该需要再建一个订单类的表单独存储然后关联得出,所以这个后续再搞
下面我们搞一个service的model,然后再搞一下MP的代码自动生成
service所在的依赖如下:
<dependencies>
<dependency>
<groupId>com.dd</groupId>
<artifactId>model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--web 需要启动项目-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 服务注册 -->
<!-- <dependency>-->
<!-- <groupId>com.alibaba.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>-->
<!-- </dependency>-->
<!-- 服务调用feign -->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-openfeign</artifactId>-->
<!-- </dependency>-->
<!-- 流量控制 -->
<!-- <dependency>-->
<!-- <groupId>com.alibaba.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>-->
<!-- </dependency>-->
<!--开发者工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
service_customer的依赖如下
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
下面建一下com.dd.CodeGet类
写入如下代码
package com.dd;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class CodeGet {
public static void main(String[] args) {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
//gc.setOutputDir(projectPath + "/src/main/java");
gc.setOutputDir("xxx\\service_customer" + "/src/main/java");
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setAuthor("xxx");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://xxx:xxx/wechatstore_bak");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("xxx");
dsc.setPassword("xxx");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("customer"); //模块名
pc.setParent("com.dd.wechatstore");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("customer");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
xxx的内容根据自己情况填写
之前点击运行
可自动生成如下内容
这时候我们建一个config,而后的分页查询需要先配置一下
在CustomerMapper类上加上@Mapper注释
接下来我们定义一下统一接口返回
在model模块下建如下内容
代码如下
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 全局统一返回结果类
*
*/
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private T data;
public Result(){}
public static <T> Result<T> build(T body, Integer code, String message) {
Result<T> result = new Result<T>();
if (body != null) {
result.setData(body);
}
result.setCode(code);
result.setMessage(message);
return result;
}
public static<T> Result<T> ok(){
return Result.ok(null);
}
/**
* 操作成功
* @param data baseCategory1List
* @param <T>
* @return
*/
public static<T> Result<T> ok(T data){
return build(data,200,"成功");
}
public static<T> Result<T> fail(){
return Result.fail(null);
}
/**
* 操作失败
* @param data
* @param <T>
* @return
*/
public static<T> Result<T> fail(T data){
return build(data, 201,"失败");
}
public Result<T> message(String msg){
this.setMessage(msg);
return this;
}
public Result<T> code(Integer code){
this.setCode(code);
return this;
}
}
返回码为200代表返回成功
返回码为201代表返回失败
接下来对Customer稍做改造
@Data
@ApiModel(description = "customer")
@TableName("customer")
public class Customer extends BaseEntity {
private static final long serialVersionUID=1L;
/**
* 客户姓名
*/
private String name;
/**
* 客户手机号
*/
private String phone;
/**
* 客户地址
*/
private String location;
/**
* 客户头像
*/
private String avatar;
}
因为一些基础字段直接沿用上面我们定义好的BaseEntity内容即可
接下来我们来写一下CustomerController里的CRUD
@RestController
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
//1 查询所有客户
@ApiOperation("查询所有客户")
@GetMapping("findAll")
public Result findAllCustomer() {
//调用service方法
List<Customer> list = customerService.list();
return Result.ok(list).message("查询数据成功");
}
//PathVariable获取占位符
//2 逻辑删除客户
@ApiOperation("逻辑删除客户")
@DeleteMapping("remove/{id}")
public Result removeCustomer(@ApiParam(name = "id", value = "ID", required = true)
@PathVariable Long id) {
boolean isSuccess = customerService.removeById(id);
if(isSuccess) {
return Result.ok(null);
} else {
return Result.fail(null);
}
}
//条件查询分页列表
//RequestBody代表以json提交,required = false表示条件指可以为空,RequestBody必须在PostMapping里使用
@ApiOperation(value = "获取分页列表")
@PostMapping("findQueryPage/{page}/{limit}")
public Result findPage(
@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true)
@PathVariable Long limit,
@ApiParam(name = "CustomerQueryVo", value = "查询对象", required = false)
@RequestBody(required = false) CustomerQueryVo customerQueryVo) {
//创建page对象,传递当前页和每页记录数
Page<Customer> pageParam = new Page<>(page, limit);
//获取条件值
String name = customerQueryVo.getName();//客户名称
String phone = customerQueryVo.getPhone();//客户手机号
String createTimeBegin = customerQueryVo.getCreateTimeBegin();//开始时间
String createTimeEnd = customerQueryVo.getCreateTimeEnd();//结束时间
String updateTimeBegin = customerQueryVo.getUpdateTimeBegin();//开始时间
String updateTimeEnd = customerQueryVo.getUpdateTimeEnd();//结束时间
//封装条件
QueryWrapper<Customer> wrapper = new QueryWrapper<>();
if(!StringUtils.isEmpty(name)) {
wrapper.like("name",name);
}
if(!StringUtils.isEmpty(phone)) {
wrapper.eq("phone",phone);
}
if(!StringUtils.isEmpty(createTimeBegin)) {
wrapper.ge("create_time",createTimeBegin);
}
if(!StringUtils.isEmpty(createTimeEnd)) {
wrapper.le("create_time",createTimeEnd);
}
if(!StringUtils.isEmpty(updateTimeBegin)) {
wrapper.ge("update_time",updateTimeBegin);
}
if(!StringUtils.isEmpty(updateTimeEnd)) {
wrapper.le("update_time",updateTimeEnd);
}
//调用方法得到分页查询结果
IPage<Customer> pageModel = customerService.page(pageParam, wrapper);
return Result.ok(pageModel);
}
@ApiOperation(value = "新增")
@PostMapping("saveCustomer")
public Result saveCustomer(@RequestBody Customer customer) {
boolean save = customerService.save(customer);
if (save) {
return Result.ok(null);
}else {
return Result.fail(null);
}
}
@ApiOperation(value = "获取")
@GetMapping("getCustomer/{id}")
public Result getCustomer(@PathVariable Long id) {
Customer customer = customerService.getById(id);
return Result.ok(customer);
}
@ApiOperation(value = "修改")
@PutMapping("updateCustomer")
public Result updateCustomer(@RequestBody Customer customer) {
boolean update = customerService.updateById(customer);
if (update) {
return Result.ok(null);
}else {
return Result.fail(null);
}
}
@ApiOperation(value = "根据id列表删除,只要能匹配出一条就成功")
@DeleteMapping("batchRemove")
public Result batchRemove(@RequestBody List<Long> idList) {
//这个删除是WHERE id IN ( ? , ? ...)操作,所以只要能匹配出一条就能成功
boolean remove = customerService.removeByIds(idList);
if (remove) {
return Result.ok(null);
}else {
return Result.fail(null);
}
}
}
其中将查询条件封装为了类,代码如下:
@Data
public class CustomerQueryVo {
@ApiModelProperty(value = "客户姓名")
private String name;
@ApiModelProperty(value = "客户手机号")
private String phone;
@ApiModelProperty(value = "客户创建时间开始")
private String createTimeBegin;
@ApiModelProperty(value = "客户创建时间结束")
private String createTimeEnd;
@ApiModelProperty(value = "客户更新时间开始")
private String updateTimeBegin;
@ApiModelProperty(value = "客户更新时间结束")
private String updateTimeEnd;
}
接下来我们建一下主类
以及创建一下配置文件
接下来在配置文件填写如下内容
# 服务端口
server.port=18080
# 服务名
spring.application.name=service-customer
# 环境设置:dev、test、prod
spring.profiles.active=dev
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://xxx:xxx/wechatstore_bak?characterEncoding=utf-8&useSSL=false
spring.datasource.username=xxx
spring.datasource.password=xxx
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
xxx的内容根据实际情况填写即可
接下来就可以运行主类了
可以看到启动没有问题
接下来配置swagger2
建立如下的module结构
创建配置类
代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
//Enable都代表开启某个功能的意思
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("wechatstore")
.apiInfo(webApiInfo())
.select()
//只显示api路径下的页面
//.paths(Predicates.and(PathSelectors.regex("/api/.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("网站-API文档")
.description("本文档描述了网站微服务接口定义")
.version("1.0")
// .contact(new Contact("wechatstore", "", ""))
.build();
}
}
记得在service的module对应的pom.xml添加依赖
<dependency>
<groupId>com.dd</groupId>
<artifactId>service_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
然后重启项目就可以进行swagger的在线测试了
输入网址:
http://localhost:18080/swagger-ui.html
可看到如下内容