当前位置 博文首页 > 文章内容

    layman的博客:Mybatis-Plus自动生成代码以及踩坑

    作者:shunshunshun18 栏目:未分类 时间:2021-10-27 20:31:50

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    1:@Data注解无效

    解决方案:IDEA安装Lombok插件,然后重启IDEA

    2:实体类驼峰命名,数据库字段无法匹配

    解决方案:mybatis-plus.configuration.map-underscore-to-camel-case=false

    #配置数据库
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    # mysql8的驱动要加上serverTimeZone=GMT/2B8
    spring.datasource.url=jdbc:mysql://localhost:3306/hanyxx?useUnicode=true&characterEncoding=utf8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=root
    #解决实体类驼峰命名,数据库转为_ 的问题(自动驼峰转换关闭)
    mybatis-plus.configuration.map-underscore-to-camel-case=false
    #配置日志
    mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    

    3:insert时报错:argument type mismatch

    解决方案:在实体类上加上:@TableId(type = IdType.AUTO)(改变主键策略,指定为自增长)

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        @TableId(type = IdType.AUTO)
        private Integer id;
        private String userName;
        private Date birthday;
        private String sex;
        private String address;
    }
    

    如果不加@TableId(type = IdType.AUTO)

    那么Mybatis_plus会采用默认的主键生成策略:雪花算法

    雪花算法: 使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0,每次生成唯一的值

    @TableId详细解释:
    在这里插入图片描述

    4:代码自动生成

    package com.banana;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.InjectionConfig;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.po.TableFill;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    /**
     * @author layman
     * @description: TODO
     * @date 2021/2/1
     */
    public class CodeGenerator {
        //91
        private static String projectPath = System.getProperty("user.dir");
        private static String DriverName ="com.mysql.jdbc.Driver";
        private static String Url = "jdbc:mysql://localhost:3306/hanyxx?useUnicode=true&useSSL=false&characterEncoding=utf8";
        private static String username = "root";
        private static String password = "root";
        /**
         * 读取控制台内容
         */
        public static String scanner(String tip) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":");
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotBlank(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }
        /**
           * @description: 全局配置
           * @author layman
         */
        public static GlobalConfig getGlobalConfig(){
            GlobalConfig gc = new GlobalConfig();
            gc.setOutputDir(projectPath + "/src/main/java");
            gc.setAuthor("layman");
            gc.setOpen(false);
            gc.setFileOverride(false); //如果存在文件是否覆盖
            gc.setServiceName("%sService"); //去掉service前面的I前缀
            gc.setIdType(IdType.AUTO); //设置主键策略为自增
            gc.setDateType(DateType.ONLY_DATE); //设置日期格式
            //gc.setSwagger2(true); // 实体属性 Swagger2 注解
            return gc;
        }
        /**
           * @description: 配置数据源
           * @author layman
         */
        public static DataSourceConfig getDataSourceConfig(){
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setDriverName(DriverName);
            dsc.setUrl(Url);
            dsc.setUsername(username);
            dsc.setPassword(password);
            dsc.setDbType(DbType.MYSQL);
            return dsc;
        }
        /**
           * @description: 包配置
           * @author layman
           * @date 2020/12/16
         */
        public static PackageConfig getPackageConfig(){
            PackageConfig pc = new PackageConfig();
            //将来代码会生成于com.banana.user的目录下
            //pc.setModuleName("user");
    
            //自定义输入模块名称
            pc.setModuleName(scanner("模块名称"));
            pc.setParent("com.banana");
            //会生成com.banana.user.entity包
            pc.setEntity("entity");
            //会生成com.banana.user.mapper包
            pc.setMapper("mapper");
            //会生成com.banana.user.Controller包
            pc.setController("Controller");
            //会生成com.banana.user.Service包
            pc.setService("Service");
            return pc;
        }
        /**
           * @description: 策略配置
           * @author layman
           * @date 2020/12/16
         */
        public static StrategyConfig getStrategyConfig(){
            StrategyConfig strategy = new StrategyConfig();
            //下划线转驼峰命名
            strategy.setNaming(NamingStrategy.underline_to_camel);
            //列名下划线转驼峰命名
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    //      strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
            //自动支持Lombok注解
            strategy.setEntityLombokModel(true);
            //设置实体类逻辑删除字段
            strategy.setLogicDeleteFieldName("deleted");
            //设置自动填充字段
            TableFill createTime = new TableFill("createTime", FieldFill.INSERT);
            TableFill updateTime = new TableFill("updateTime", FieldFill.INSERT_UPDATE);
            List<TableFill> list = new ArrayList<>();
            list.add(createTime);
            list.add(updateTime);
            strategy.setTableFillList(list);
            //设置乐观锁
            strategy.setVersionFieldName("version");
            //设置下划线命名 localhost:8080/hello_id_2
            strategy.setControllerMappingHyphenStyle(true);
            //设置restful的驼峰命名
            strategy.setRestControllerStyle(true);
            // 公共父类
            //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
            // 写于父类中的公共字段
            //strategy.setSuperEntityColumns("id");
            //strategy.setInclude("user","product"); 设置只映射生成两张表:user表和product表
            //配置生成的表由控制台输入
            strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            return strategy;
        }
        public static void main(String[] args) {
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
            // 1.全局配置
            GlobalConfig gc = CodeGenerator.getGlobalConfig();
            mpg.setGlobalConfig(gc);
            // 2.数据源配置
            DataSourceConfig dsc = CodeGenerator.getDataSourceConfig();
            mpg.setDataSource(dsc);
            // 3.包配置
            PackageConfig pc = CodeGenerator.getPackageConfig();
            mpg.setPackageInfo(pc);
            // 4.策略配置
            StrategyConfig strategy = CodeGenerator.getStrategyConfig();
            mpg.setStrategy(strategy);
    
            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };
    
            // 如果模板引擎是 freemarker
            String templatePath = "/templates/mapper.xml.ftl";
            // 如果模板引擎是 velocity
            // String templatePath = "/templates/mapper.xml.vm";
    
            // 自定义输出配置,自定义配置会被优先输出
            List<FileOutConfig> focList = new ArrayList<>();
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            /*
            cfg.setFileCreate(new IFileCreate() {
                @Override
                public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                    // 判断自定义文件夹是否需要创建
                    checkDir("调用默认方法创建的目录,自定义目录用");
                    if (fileType == FileType.MAPPER) {
                        // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                        return !new File(filePath).exists();
                    }
                    // 允许生成模板文件
                    return true;
                }
            });
            */
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
    
            // 配置模板,不在mapper中新建xml目录并生成xml文件
            TemplateConfig templateConfig = new TemplateConfig();
            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            mpg.execute();
        }
    }
    
    cs