代码生成器
pom.xml文件中
<?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><groupId>com.yase</groupId><artifactId>spmp</artifactId><version>0.0.1-SNAPSHOT</version><name>spmp</name><description>spmp</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.7.6</spring-boot.version></properties><dependencies><!--模板引擎--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
<!-- web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<!--热部署工具--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency>
<!-- mysql--><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency>
<!-- lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
<!-- test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<!-- 整合swagger--><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
<!-- mybatisplus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version></dependency>
<!-- mybatisplus代码生成器依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.2</version></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version><configuration><mainClass>com.yase.spmp.SpmpApplication</mainClass><skip>true</skip></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>
在Test文件夹中创建测试类
package com.yase.spmp;import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;//此处代码可以自动生成系列文件
@SpringBootTest
public class TestGenerator {@Testpublic void testGenerator(){FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8", "root", "root").globalConfig(builder -> {builder.author("jiangnan") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir(".\\src\\main\\java"); // 指定输出目录})
//不了解忽略
// .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
// int typeCode = metaInfo.getJdbcType().TYPE_CODE;
// if (typeCode == Types.SMALLINT) {
// // 自定义类型转换
// return DbColumnType.INTEGER;
// }
// return typeRegistry.getColumnType(metaInfo);
//
// })).packageConfig(builder -> {builder.parent("com.yase") // 设置父包名.moduleName("system"); // 设置父包模块名
// .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径,此处可以使用默认的}).strategyConfig(builder -> {builder.addInclude("i_emp") // 设置需要生成的表名.addTablePrefix("i_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();}
}
导入swagger3的配置类
package com.yase.system.config;import io.swagger.annotations.ApiOperation;
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.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;@Configuration
public class Swagger3Config {/*** 创建API应用* apiInfo() 增加API相关信息* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,* 本例采用指定扫描的包路径来定义指定要建立API的目录。** @return*/@Beanpublic Docket restApi() {return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build();}//创建该API的基本信息(这些基本信息会展现在文档页面中)private ApiInfo apiInfo() {return new ApiInfoBuilder().title("title").description("https://baidu.com") .termsOfServiceUrl("https://baidu.com").contact(new Contact("dada", "https://baidu.com", "2391356197@qq.com")).build();}
}
创建状态码接口
package com.yase.system.util;public interface ResultCode {//前端element-uiInteger SUCCESS = 20000;Integer ERROR = 20001;
}
规定返回结果类
package com.yase.system.util;import lombok.Data;
import lombok.experimental.Accessors;
import java.util.HashMap;
import java.util.Map;//返回结果类
@Data
@Accessors(chain = true)
public class Result {//操作是否成功private Boolean isSuccess;//状态码private Integer code;//消息private String message;//返回数据private Map<String,Object> data;//操作成功public static Result success(){return new Result().setIsSuccess(true).setCode(ResultCode.SUCCESS).setMessage("操作成功").setData(new HashMap<>());}//操作失败public static Result error(){return new Result().setIsSuccess(false).setCode(ResultCode.ERROR).setMessage("操作失败").setData(new HashMap<>());}//用户传入数据public Result setData(HashMap<String,Object> data) {this.data = data;return this;}public Result setData(String key,Object value){this.data.put(key,value);return this;}
}
在control类创建相关功能
package com.yase.system.controller;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yase.system.entity.Emp;
import com.yase.system.service.IEmpService;
import com.yase.system.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;/*** <p>* 前端控制器* </p>** @author jiangnan* @since 2024-05-14*/
@RestController
@RequestMapping("/system/emp")
@Api("管理信息")
public class EmpController {@Resourceprivate IEmpService service;//?@GetMapping("/{id}")@ApiOperation("按照id查询数据数据")public Result selectOneData(@PathVariable Integer id){Emp byId = service.getById(id);return Result.success().setData("emp",byId);}//分页,需要传入当前的页码current和每页显示的大小size@GetMapping("/{current}/{size}")@ApiOperation("给定页码和每页大小,显示信息")public Result selectPage(@PathVariable Integer current,@PathVariable Integer size){//此处需要导入page的分页配置类Page<Emp> page = new Page<>(current,size);//无需给page获取返回对象service.page(page);return Result.success().setData("page",page);}@ApiOperation("查询所有数据")@GetMappingpublic Result select(){List<Emp> list = service.list();/*两种返回方式HashMap<String,Object> map = new HashMap<>();map.put("list",list);return Result.success().setData(map);*/return Result.success().setData("list",list);}@PostMapping@ApiOperation("保存数据")public Result save(@RequestBody Emp emp){//判断返回的状态,true返回成功,false返回errorboolean b = service.save(emp);return b?Result.success():Result.error();}@PutMapping@ApiOperation("更新数据")public Result update(@RequestBody Emp emp){return service.updateById(emp) ? Result.success():Result.error();}@DeleteMapping("/{id}")@ApiOperation("删除数据")public Result delete(@PathVariable Integer id){return service.removeById(id) ? Result.success():Result.error();}}
最后在AppServer中添加扫描mapper,即可完成
@MapperScan(“com.yase.system.mapper”)