问题描述【项目搭建】
实现购物车模块的CRUD,用户、商品分类、商品、商品-用户中间表
解决方案
新建项目
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: 8081servlet:context-path: /spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/demotest1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: lyjajackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8serialization:write-dates-as-timestamps: falsemybatis-plus:configuration:map-underscore-to-camel-case: trueauto-mapping-behavior: fulllog-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath*:mapper/**/*Mapper.xmlglobal-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 {@Testpublic 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); // 重新生成时文件是否覆盖// UserServiegc.setServiceName("%sService"); // 去掉 Service 接口的首字母Igc.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.empmspc.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();}
}
启动该类,生成项目结构
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);@Overridepublic void insertFill(MetaObject metaObject) { // 添加的自动填充// createTime、updateTime实体类中属性名this.setFieldValByName("gmtCreate", new Date(), metaObject);this.setFieldValByName("gmtModified", new Date(), metaObject);}@Overridepublic 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 {// 分页插件@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}// 逻辑删除插件@Beanpublic 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 {@Beanpublic 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