MyBatis-Plus(day5_代码生成机制)

在Mybatis-Plus中,内置了代码生成器,我们可以通过该工具,生成我们需要的代码,例如:entity层,controller层,mapper层,service层。如此一来,我么就可以节省编码的时间,优化开发。

官方介绍: AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

官方文档:

https://baomidou.com/pages/d357af/#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

一、代码生成器实现过程

1. 添加依赖

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖: 一定要注意版本问题,否则可能出现报错。

  • 添加 代码生成器 依赖
<!--代码生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
  • 添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。(使用默认即可)
 <!--模板引擎依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

2.代码生成程序(注意:一定不能导错包,要用mybatis-plus中的包)

package com.janson.generate;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author Janson
 * @Date 2022/3/15 8:33
 * @Version 1.0
 */
public class CodeGenerate {
    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("janson");
        gc.setOpen(false);
        gc.setFileOverride(false); //是否覆盖
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("11111");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("generate");
        pc.setParent("com.janson");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setController("controller");
        pc.setService("service");
        mpg.setPackageInfo(pc);
/*
*/
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);  //自动加上lombok
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        //strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setInclude("user");   //设置映射表名
        strategy.setLogicDeleteFieldName("deleted"); // 逻辑删除
        //自动填充
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
        List<TableFill> fillList = new ArrayList();
        fillList.add(createTime);
        fillList.add(updateTime);
        strategy.setTableFillList(fillList);
        //乐观锁
        strategy.setVersionFieldName("version");
        //restful风格
        strategy.setRestControllerStyle(true);
        //localhost:8080/hello_id_1 或者2
        strategy.setControllerMappingHyphenStyle(true);
        //strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

3.执行main方法,生成代码

在这里插入图片描述

4.然后将 Swagger配置引入到程序中,前边已经学习过,不了解可以看下边文章

https://blog.csdn.net/qq_42102911/article/details/123295890

注意:一定注意 springboot 版本与 Swagger版本的对应,否则可能会报错,springboot: 2.1.7.RELEASE
Swagger:2.9.2

5.检查生成的 User 实体类,发现一些问题,修改如下

将LocalDateTime 修改为 Date,否则自动填充功能就无法实现了,还有一点,在没有采用生成代码时,更新的自动填充要加 update = “now” ,才能实现自动填充,但是采用生成代码机制,生成的更新自动填充,不需要加 update = “now” ,加上反而报错,报错如下

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @ApiModelProperty(value = "更新时间")
    //@TableField(fill = FieldFill.UPDATE,update = "now")
    @TableField(fill = FieldFill.UPDATE)
    //自动生成的
    //private LocalDateTime updateTime;
    //要修改成 Date
    private Date updateTime;

报错如下:
nested exception is org.springframework.jdbc.BadSqlGrammarException:

 ERROR 14652 --- [io-8081-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: 
### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: Unknown error 1054
### The error may exist in com/janson/generate/mapper/UserMapper.java (best guess)
### The error may involve com.janson.generate.mapper.UserMapper.updateById-Inline
### The error occurred while setting parameters

在这里插入图片描述

6.在controller中写入相应的请求,@requestMapping

启动程序,如果能正常启动,就可以取http://localhost:8081/swagger-ui.html中测试了接口了。
无法启动,看看我的解决错误的方法吧。

  • https://blog.csdn.net/qq_42102911/article/details/123495683
  • https://blog.csdn.net/qq_42102911/article/details/123493860
  • https://blog.csdn.net/qq_42102911/article/details/123510142
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Janson666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值