问题描述【项目搭建】
实现购物车模块的CRUD,用户、商品分类、商品、商品-用户中间表
解决方案
新建项目
![](https://i-blog.csdnimg.cn/blog_migrate/331ed030e05f67ddf1ccf57f40c53187.png)
![](https://i-blog.csdnimg.cn/blog_migrate/8020febc35c9e9e8f8364d4c3eb65754.png)
2、pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--web项目起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--MyBatis 整合 SpringBoot 的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MySQL驱动的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- SpringBoot 整合 MyBatisPlus 的起步依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--velocity 模板引擎, Mybatis Plus 代码生成器需要-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<!--Swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--Swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3、
(1)application.properties
# 服务器端口号
server.port=8008
# 数据库的连接
spring.datasource.url=jdbc:mysql://localhost:3306/demotest1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
# 配置mapper映射文件
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
# 日期、时间的格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
# MyBatisPlus的日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(2)application.yml
server:
port: 8081
servlet:
context-path: /
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/demotest1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: lyja
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
write-dates-as-timestamps: false
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 0
# 删除后
logic-delete-value: 1
4、创建 CodeGenerator代码生成器类
package com.test.demo;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
public class CodeGenerator {
@Test
public void test() {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
// 代码生成的位置
gc.setOutputDir("E:\\IDEA_Code\\Scode\\Test\\DemoTest" + "/src/main/java");
gc.setAuthor("xiao");
gc.setOpen(false); // 生成后是否打开资源管理器
gc.setFileOverride(false); // 重新生成时文件是否覆盖
// UserServie
gc.setServiceName("%sService"); // 去掉 Service 接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR); // 主键策略
gc.setDateType(DateType.ONLY_DATE); // 定义生成的实体类中日期类型
gc.setSwagger2(true); // 开启 Swagger2 模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/demotest1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
// 包 com.demo.empms
pc.setParent("com.test"); // 设置根包
pc.setController("controller");
pc.setEntity("model");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user","type","commidity","goods"); // 数据库中的表名,多个表名中间使用逗号隔开
strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); // 生成实体时去掉表前缀
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();
}
}
启动该类,生成项目结构
![](https://i-blog.csdnimg.cn/blog_migrate/4e13ca5f32e830fee85672121a053510.png)
5、配置MyBatis-Plus的逻辑删除、分页、自动填充、Swagger配置
(1)在src/main/java/config下创建自动填充类AutoFill
package com.test.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class AutoFill implements MetaObjectHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(AutoFill.class);
@Override
public void insertFill(MetaObject metaObject) { // 添加的自动填充
// createTime、updateTime实体类中属性名
this.setFieldValByName("gmtCreate", new Date(), metaObject);
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) { // 修改的自动填充
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
}
(2)在src/main/java/config下创建逻辑删除、分页MPConfig类
package com.test.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.test.mapper")
public class MPConfig {
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
// 逻辑删除插件
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
(3)在src/main/java/config下创建SwaggerConfig类
package com.xzy.springboot.config;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;
@Configuration // 配置类
@EnableSwagger2 // swagger注解
public class SwaggerConfig {
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合MyBatisPlus实现员工的增删改查-API文档")
.description("本文档描述了员工增删改查案例中接口定义")
.version("1.0")
.contact(new Contact("陈经理", "https://www.baidu.com", "5977649949@qq.com"))
.build();
}
}
6、在根包下创建启动类Application
package com.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@MapperScan("com.test.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7、实现CRUD功能
8、先运行启动类,进行Swagger测试:
在浏览器地址栏输入:http://localhost:8008/swagger-ui.html