栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis-Plus(day5

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

添加 代码生成器 依赖

        
            com.baomidou
            mybatis-plus-generator
            3.3.0
        

添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。(使用默认即可)

 
        
            org.apache.velocity
            velocity-engine-core
            2.3
        
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;



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 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/123495683https://blog.csdn.net/qq_42102911/article/details/123493860https://blog.csdn.net/qq_42102911/article/details/123510142

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号