springboot整合mybatisPlus代码生成器

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();
    }
}
​

SpringBoot MybatisPlus代码生成器是一种用于生成MybatisPlus代码的工具,可以帮助我们快速生成数据库表的实体类、Mapper接口、Service接口和Controller类等代码。 我们可以到Mybatis-plus官网的源码仓库页面下载MybatisPlus的源码,链接为https://gitee.com/baomidou/mybatis-plus或https://github.com/baomidou/mybatis-plus。 在使用代码生成器时,我们需要在模板中编写我们想要加入的内容,可以包括变量、方法等。然后将这些模板放在项目的templates目录下,生成代码时会自动读取该目录下的模板文件。然后,我们需要设置模板的路径,并在启动项目后运行生成代码类的main方法,即可使我们编写的模板生效。 通过使用SpringBoot MybatisPlus代码生成器,我们可以大大提高开发效率,减少重复劳动,让我们能够更专注于业务逻辑的开发。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot+MybatisPlus+代码生成器整合示例](https://download.csdn.net/download/weixin_38639747/12727040)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot整合Mybatis-plus之代码生成](https://blog.csdn.net/weixin_44263023/article/details/110959305)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值