Mybatis-Plus自动生成代码

1.创建项目并引入依赖

        创建一个SpringBoot项目,然后再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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.generation.code</groupId>
    <artifactId>mybatis-plus-generation-Code</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plus-generation-Code</name>
    <description>mybatis-plus-generation-Code</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <!-- SpringBoot集成Mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!--  Mybatis-plus代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--模板默认引擎velocity-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- swagger2 配置 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <!--将src/main/java目录下的所有xml文件都作为项目的资源文件,编译打包时会进行预编译并打包进去-->
            <resource>
                <!-- xml放在java目录下-->
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <!--filtering标签默认是false,表示include标签中的文件不需要预编译并打入包中;true表示需要被预编译打包-->
                <filtering>true</filtering>
            </resource>
            <!--将src/main/resources 目录下的所有xml文件都作为项目的资源文件,编译打包时会进行预编译并打包进去-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.txt</include>
                    <include>**/*.png</include>
                    <include>**/*.properties</include>
                    <include>**/*.ini</include>
                    <include>**/*.yml</include>
                    <include>**/*.js</include>
                    <include>**/*.html</include>
                    <include>**/*.xls</include>
                    <include>**/*.xlsx</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>
2.配置yml文件

        applicatiom.yml

server:
  port: 8182

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource          #数据源类型
    driver-class-name: com.mysql.cj.jdbc.Driver       #数据库驱动
    url: jdbc:mysql://localhost:3306/self_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
    username: root
    password: Root123
    hikari:
      connection-timeout: 30000       # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
      minimum-idle: 5                 # 最小连接数
      maximum-pool-size: 20           # 最大连接数
      auto-commit: true               # 自动提交
      idle-timeout: 600000            # 连接超时的最大时长(毫秒)超时则被释放(retired),默认:10分钟
      pool-name: DateSourceHikariCP     # 连接池名字
      max-lifetime: 1800000           # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
      connection-test-query: SELECT 1
  #Springfox使用的路径匹配是基于AntPathMatcher
  #Spring Boot使用的是PathPatternMatcher
  #为了解决swagger2和springboot冲突问题
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

#配置日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  #指定sql映射文件
  mapper-locations: classpath:/org/bxl/mapper/xml/*.xml

3.编写生成代码的方法

        这里把测试方法放在test测试包下MybatisPlusGenerationCodeTest.java

package com.generation.code;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.ibatis.annotations.Mapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class MybatisPlusGenerationCodeTest{

    /**
     * 获取yml配置文件中的url
     */
    @Value("${spring.datasource.url}")
    private String url;
    /**
     * 获取yml配置文件中的username
     */
    @Value("${spring.datasource.username}")
    private String username;
    /**
     * 获取yml配置文件中的password
     */
    @Value("${spring.datasource.password}")
    private String password;

    @Test
    @DisplayName("自动生成entity、service、mapper、controller")
    public void execute() {
        String userDir = System.getProperty("user.dir");
        System.out.println("user.dir:" + userDir);
        String outputDir = userDir + "\\src\\main\\java";       //指定输出目录(一般指定到java目录)
        //设置mapperXml生成路径,这里是Mapper配置文件的路径,建议使用绝对路径
        String xmlPath = outputDir + "\\com\\generation\\code\\mapper\\xml";
        //需要生成相关代码的表名称
        List<String> tableList = new ArrayList<>();
        tableList.add("generals");
        tableList.add("student");
        tableList.add("reservoir");
        generationCode(outputDir,xmlPath,tableList);
        System.out.println("代码生成完毕!");

    }

    public void generationCode(String outputDir,String xmlPath,List<String> tableList){
        //创建代码生成器
        FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(this.url,this.username,this.password);
        //全局配置
        fastAutoGenerator.globalConfig(gc->
                gc.author("白晓楼")             //作者
                        .enableSwagger()
                        .dateType(DateType.TIME_PACK)
                        .commentDate("yyyy-MM-dd")
                        .outputDir(outputDir)
        );
        //包配置
        fastAutoGenerator.packageConfig(fg->{
            Map<OutputFile, String> pathInfo = new HashMap<>();
            pathInfo.put(OutputFile.xml,xmlPath);
            fg.parent("com.generation.code");       //包名称-指定生成代码在哪个包
            fg.moduleName("");
            fg.pathInfo(pathInfo);
        });
        //策略配置
        fastAutoGenerator.strategyConfig(strategy->{
            //设置需要生成的表名称
            tableList.stream().forEach(name -> {
                strategy.addInclude(name);
            });
            //格式化Services的命名策略,没有这个配置配置的话,名称前面会加上一个I
            //如:UserService 和 UserServiceImpl 变成 IUserService和IUserServiceImpl
            strategy.serviceBuilder()
                    .enableFileOverride()         //开启service文件覆盖配置
                    .formatServiceFileName("%sService")
                    .formatServiceImplFileName("%sServiceImpl");
            //生成Controller
            strategy.controllerBuilder()
                    .enableFileOverride()       //开启Controller文件覆盖,默认是false
                    .enableRestStyle(); //开启生成@RestController控制器
            //生成mapper
            strategy.mapperBuilder()
                    .enableFileOverride()       //开启Mapper文件覆盖,默认是false
                    .enableMapperAnnotation()
                    .mapperAnnotation(Mapper.class);        //开启mapper注解
            //生成实体类
            strategy.entityBuilder()
                    .enableLombok()                     //开启Lombok
                    .enableTableFieldAnnotation()       //开启生成实体时生成字段注解
                    .enableFileOverride()       //开启实体类文件覆盖,默认是false
            ;
        });
        //使用Freemarker引擎,需要引入依赖(默认是Velocity引擎模板)
//        fastAutoGenerator.templateEngine(new FreemarkerTemplateEngine());
        fastAutoGenerator.templateEngine(new VelocityTemplateEngine());
        fastAutoGenerator.execute();        //执行以上配置
    }

}

    

4.查看结果

        执行execute()方法,生成相关代码。请注意代码中的包名称要根据实际情况进行修改;

        整体项目架构

        Generals.java

package com.generation.code.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

/**
 * 古代大将信息表
 * @author 白晓楼
 * @since 2023-09-07
 */
@Getter
@Setter
@TableName("generals")
@ApiModel(value = "Generals对象", description = "古代大将信息表")
public class Generals implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("编号")
    @TableId("id")
    private Integer id;

    @ApiModelProperty("名称")
    @TableField("g_name")
    private String gName;

    @ApiModelProperty("称号")
    @TableField("nick_name")
    private String nickName;

    @ApiModelProperty("所在朝代")
    @TableField("dynasty")
    private String dynasty;

    @ApiModelProperty("武力值")
    @TableField("force_value")
    private Integer forceValue;

    @ApiModelProperty("生平简介")
    @TableField("brief")
    private String brief;

    @ApiModelProperty("性别:1-男/0-女")
    @TableField("gender")
    private Integer gender;

    @ApiModelProperty("备注")
    @TableField("remarks")
    private String remarks;
}

        GeneralsMapper.java

package com.generation.code.mapper;

import com.generation.code.entity.Generals;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * 古代大将信息表 Mapper 接口
 * @author 白晓楼
 * @since 2023-09-07
 */
@Mapper
public interface GeneralsMapper extends BaseMapper<Generals> {

}

        GeneralsMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.generation.code.mapper.GeneralsMapper">

</mapper>

        GeneralsService.java

package com.generation.code.service;

import com.generation.code.entity.Generals;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * 古代大将信息表 服务类
 * @author 白晓楼
 * @since 2023-09-07
 */
public interface GeneralsService extends IService<Generals> {

}

        GeneralsServiceImpl.java

package com.generation.code.service.impl;

import com.generation.code.entity.Generals;
import com.generation.code.mapper.GeneralsMapper;
import com.generation.code.service.GeneralsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 古代大将信息表 服务实现类
 * @author 白晓楼
 * @since 2023-09-07
 */
@Service
public class GeneralsServiceImpl extends ServiceImpl<GeneralsMapper, Generals> implements GeneralsService {

}

        GeneralsController.java

package com.generation.code.controller;

import com.generation.code.entity.Generals;
import com.generation.code.service.GeneralsService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 古代大将信息表 前端控制器
 * @author 白晓楼
 * @since 2023-09-07
 */
@RestController
@RequestMapping("/generals")
public class GeneralsController {

}
5.测试

        挑选一个Controller,写一个查询数据库的方法,测试生成代码是否是可用的

@RestController
@RequestMapping("/generals")
public class GeneralsController {

    @Resource
    private GeneralsService generalsService;

    @GetMapping("/list")
    @ApiOperation(value = "获取Generals列表",notes = "获取Generals列表")
    public List<Generals> getGeneralsList(){
        return generalsService.list();
    }

}

        启动项目,用postman测试结果

        查询数据成功,表示自动生成的代码是没问题的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值