pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入MybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.5</version>
</dependency>
<!--代码生成器:模板引擎依赖 Velocity-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
配置yml文件
server:
port: 9090
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2b8
username: root
password: root
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
mybatis:
mapper-locations: classpath:mapper/*.xml
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
创建配置文件
mybatis-plus的分页插件
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("org.yuni.parent.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
配置knife4jConfig
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Knife4jConfig {
/**
* 地址:http://127.0.0.1:9090/doc.html
*
*/
@Bean
public GroupedOpenApi adminApi() { // 创建了一个api接口的分组
return GroupedOpenApi.builder()
.group("admin-api") // 分组名称
.pathsToMatch("/admin/**") // 接口请求路径规则
.build();
}
/***
* @description 自定义接口信息
*/
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("API接口文档")
.version("1.0")
.description("API接口文档")
.contact(new Contact().name("yuni"))); // 设定作者
}
}
创建代码生成器工具类
模板
entity.java.vm
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.v3.oas.annotations.media.Schema;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
*
*/
#if(${entityLombokModel})
@Getter
@Setter
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${swagger})
@Schema(description = "${entity}对象")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#elseif(${entitySerialVersionUID})
public class ${entity} implements Serializable {
#else
public class ${entity} {
#end
#if(${entitySerialVersionUID})
private static final long serialVersionUID = 1L;
#end
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
#if(${swagger})
@Schema(description ="${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${field.versionField})
@Version
#end
## 逻辑删除注解
#if(${field.logicDeleteField})
@TableLogic
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------
#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
#if(${chainModel})
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(${activeRecord})
@Override
public Serializable pkVal() {
#if(${keyPropertyName})
return this.${keyPropertyName};
#else
return null;
#end
}
#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}
myController.java.vm
package ${package.Controller};
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* $!{table.comment} 前端控制器
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/admin/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
@Tag(name = "${table.comment}接口")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
@Resource
private ${table.serviceName} ${table.entityPath}Service;
// 新增或者更新
@PostMapping("/add")
@Operation(summary = "新增或者修改")
public boolean save(@RequestBody ${entity} ${table.entityPath}){
return ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
}
@DeleteMapping("/{id}")
@Operation(summary = "根据id删除")
public Boolean delete(@PathVariable Integer id){
return ${table.entityPath}Service.removeById(id);
}
@PostMapping("/del/batch")
@Operation(summary = "批量删除")
public boolean deleteBatch(@RequestBody List<Integer> ids){
return ${table.entityPath}Service.removeByIds(ids);
}
@GetMapping
@Operation(summary = "查询全部")
public List<${entity}> findAll(){
return ${table.entityPath}Service.list();
}
@GetMapping("/{id}")
@Operation(summary = "根据id查询")
public ${entity} findOne(@PathVariable Integer id){
return ${table.entityPath}Service.getById(id);
}
@GetMapping("/page")
@Operation(summary = "分页查询")
public Page<${entity}> findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize){
QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
queryWrapper.orderByDesc("id");
return ${table.entityPath}Service.page(new Page<>(pageNum,pageSize),queryWrapper);
}
}
#end
CodeGen
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import java.sql.Types;
import java.util.Collections;
public class CodeGen {
public static void main(String[] args) {
// 数据库配置信息
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
//表名
String TableName = "sys_role";
// 当前项目路径
String currentPath = "D:\\小白轻松学springboot+vue\\管理系统\\demo";
String codeOutputDir = currentPath + "/src/main/java";
// mapperXml 生成路径
String mapperXmlPath = currentPath + "/src/main/resources/mapper";
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
// 设置作者
builder.author("与你")
// 开启 swagger 模式
.enableSwagger()
// 指定输出目录
.outputDir(codeOutputDir);
})
.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.example")
// 设置父包模块名
.moduleName("demo")
// pojo 实体类包名
.entity("entity")
// Service 包名
.service("service")
// ***ServiceImpl 包名
.serviceImpl("service.impl")
// Mapper 包名
.mapper("mapper")
// Mapper XML 包名
.xml("mapper.xml")
// Controller 包名
.controller("controller")
// 设置 mapperXml 生成路径
.pathInfo(Collections.singletonMap(OutputFile.xml, mapperXmlPath));
})
.strategyConfig(builder -> {
// 设置需要生成的表名
builder.addInclude(TableName)
// 设置过滤表前缀
.addTablePrefix("t_", "sys_")
// Entity 配置
.entityBuilder()
// 开启 lombok 模型
.enableLombok()
// 覆盖已生成文件
.enableFileOverride()
// Controller 配置
.controllerBuilder()
// 开启生成 @RestController 控制器
.enableRestStyle()
// 覆盖已生成文件
.enableFileOverride()
// Service 配置
.serviceBuilder()
// 覆盖已生成文件
.enableFileOverride()
// Mapper 配置
.mapperBuilder()
// 覆盖已生成文件
.enableFileOverride();
})
// // 默认的是 Velocity引擎模板
// .templateEngine(new FreemarkerTemplateEngine())
.templateConfig(builder -> {
builder.entity("/templates/entity.java") // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
.build(); // 指定模板
builder.controller("/templates/myController.java") // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
.build(); // 指定模板
})
.execute();
}
}