SpringBoot + MyBatis-Plus + Swagger快速创建后台项目
本文主要用于记录综合课程设计Ⅲ中的学习的后台相关插件使用…
项目简介
快速开始
1、GitHub创建项目
我的GitHub地址
- 新建一个代码仓库,用于管理项目代码
2、使用idea将代码下载到本地并新建Springboot模块
- 新建SpringBoot项目模块
- 勾选相关依赖
- 项目创建成功
3、创建数据库
- 在navcat中新建数据库
新建employee表
4、开始编写代码
1. 将application.properties
文件删除并新建application.yml
、application-dev.yml
、application-prod.yml
。
2. 分别编写对应的配置文件
application.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server: port: 8080 servlet: context-path: / spring: profiles: active: prod datasource: druid: url: jdbc:mysql://localhost:3306/weixin?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2b8 username: root password: root initial-size: 1 min-idle: 1 max-active: 20 test-on-borrow: true driver-class-name: com.mysql.cj.jdbc.Driver
|
application-dev.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| server: port: 8081 servlet: context-path: / spring: datasource: url: jdbc:mysql://localhost:3306/weixin?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2b8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus: mapper-locations: classpath:mapper/*Mapper.xml type-aliases-package: com.marlowe.music.entity configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
application-prod.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| server: port: 8081 servlet: context-path: / spring: datasource: url: jdbc:mysql://localhost:3306/weixin?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2b8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus: mapper-locations: classpath:mapper/*Mapper.xml type-aliases-package: com.marlowe.music.entity configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
3. 引入相关依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.6</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.hankcs</groupId> <artifactId>hanlp</artifactId> <version>portable-1.1.5</version> </dependency>
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.0</version> </dependency>
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency>
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency>
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
|
4. 创建公共包
新建commons包,用于统一结果处理,统一异常处理,以及代码生成器配置
- 统一结果处理
编写错误代码类
ErrorCode.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public enum ErrorCode {
SUCCESS("200", "请求成功"),
ERROR("500", "请求失败"); private String code; private String message;
public String getCode() { return this.code; }
public String getMessage() { return this.message; }
ErrorCode(String _code, String _message) { this.code = _code; this.message = _message; } }
|
编写统一结果接口
IResult.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public interface IResult<T> {
String getMsg();
String getCode();
T getData(); }
|
编写统一结果实现类
Result.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| @Data @AllArgsConstructor @NoArgsConstructor public class Result<T> implements Serializable, IResult<T> {
private String code; private String msg; private T data;
public static Result ok() { return new Result(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMessage(), null); }
public static Result ok(String msg) { return new Result(ErrorCode.SUCCESS.getCode(), msg, null); }
public static Result ok(String msg, Object data) { return new Result(ErrorCode.SUCCESS.getCode(), msg, data); }
public static Result ok(Object data) { return new Result(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMessage(), data); }
public static Result error() { return new Result(ErrorCode.ERROR.getCode(), ErrorCode.ERROR.getMessage(), null); }
public static Result error(ErrorCode errorCode) { return new Result(errorCode.getCode(), errorCode.getMessage(), null); }
public static Result error(String code, String msg) { return new Result(code, msg, null); }
public static Result error(String code, String msg, Object data) { return new Result(code, ErrorCode.ERROR.getMessage(), data); }
public static Result error(ErrorCode errorCode, String msg) { return new Result(ErrorCode.ERROR.getCode(), msg, null); }
@Override public String getMsg() { return this.msg; }
@Override public String getCode() { return this.code; }
@Override public T getData() { return this.data; }
@Override public String toString() { return "Result{" + "code='" + code + '\'' + ", msg='" + msg + '\'' + ", data=" + data + '}'; } }
|
- 编写代码自动生成类,并修改配置
CodeGenerator.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| public class CodeGenerator {
public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); }
public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("marlowe"); gc.setOpen(false); mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/music?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setParent("com.marlowe.music"); pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { } }; String templatePath = "/templates/mapper.xml.ftl"; List<FileOutConfig> focList = new ArrayList<>();
cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);
StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setInclude(scanner("表名").split(",")); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true);
mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
|
5. 创建配置类包
- 编写Swagger配置类
SwaggerConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| @Configuration @EnableSwagger2 public class SwaggerConfig {
@Bean public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("Marlowe") .select() .apis(RequestHandlerSelectors.basePackage("com.marlowe.music.controller")) .build(); }
public ApiInfo apiInfo() {
Contact contact = new Contact("Marlowe", "https://xmmarlowe.github.io", "marlowe246@qq.com");
return new ApiInfo("SpringBoot-VUE-Music API Documentation", "Api Documentation", "v1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
|
- 编写Pagehelper配置类
PageHelperConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Configuration public class PageHelperConfig {
@Bean public PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("offsetAsPageNum", "true"); properties.setProperty("rowBoundsWithCount", "true"); properties.setProperty("reasonable", "true"); pageHelper.setProperties(properties); return pageHelper; } }
|
6. 运行CodeGenerator
得到相关代码
- 编写service接口
IEmployeeService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public interface IEmployeeService extends IService<Employee> {
boolean addEmployee(Employee employee);
boolean delete(int id);
PageInfo<Employee> findByName(String name,int pageNo,int pageSize);
}
|
- 编写service实现类
EmployeeServiceImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| @Service public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
@Autowired private EmployeeMapper employeeMapper;
@Override public boolean addEmployee(Employee employee) { return employeeMapper.insert(employee) > 0; }
@Override public boolean delete(int id) { return employeeMapper.deleteById(id) > 0; }
@Override public PageInfo<Employee> findByName(String name, int pageNo, int pageSize) { PageHelper.startPage(pageNo, pageSize); QueryWrapper<Employee> queryWrapper = new QueryWrapper<>(); queryWrapper.like("name", name); List<Employee> employees = employeeMapper.selectList(queryWrapper); PageInfo<Employee> pageInfo = new PageInfo(employees); return pageInfo; } }
|
- 编写controller
EmployeeController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| @RestController @Api(tags = "员工管理控制器") @RequestMapping("/employee") public class EmployeeController {
@Autowired private EmployeeServiceImpl employeeService;
@ApiOperation(value = "添加员工") @PostMapping("add") public String addEmployee(@RequestBody Employee employee) { boolean b = employeeService.addEmployee(employee); if (b) { return "添加成功"; } else { return "添加失败"; }
}
@ApiOperation(value = "根据id删除员工") @PostMapping("delete/{id}") public Result deleteEmployee(@PathVariable int id) { boolean delete = employeeService.delete(id); if (delete) { return Result.ok("删除成功"); } else { return Result.ok("删除失败"); } }
@ApiOperation(value = "通过姓名分页查找员工") @PostMapping("find/{name}/{pageNo}/{pageSize}") public Result<List<Employee>> findEmployee(@PathVariable String name, @PathVariable int pageNo, @PathVariable int pageSize) { PageInfo<Employee> pageInfo = employeeService.findByName(name, pageNo, pageSize); List<Employee> employees = pageInfo.getList(); return Result.ok(employees); }
}
|
- 在启动类加@MapperScan(“mapper的包名”)
1
| @MapperScan("com.marlowe.whell.mapper")
|
启动代码
访问swagger在线文档
swagger在线文档
分别测试所有接口即可。
参考资料
Marlowe’s的个人博客
项目地址