Mybatis Plus 代码生成器 columnNaming 大驼峰转小驼峰

Mybatis plus提供的数据库字段到实体类属性的转换策略,只有下划线转小驼峰(数据库字段为user_name,转为实体属性为userName)。如果情况是数据表字段为大驼峰式UserName,转成实体属性变成小驼峰式userName,参考github的issue(https://github/baomidou/mybatis-plus/issues/1345),需要覆写INameConvert的两个方法,具体思路如下。

1、使用Google guava工具类处理大小驼峰和各种下划线的转换,加载依赖包(gradle)

    compile group: 'com.google.guava', name: 'guava', version: '28.1-jre'

2、修改官方的代码生成器代码(https://mp.baomidou/guide/generator.html)。在其策略配置中,增加设置nameCovert属性,覆写InameCovert的两个方法。entityNameConvert方法是表名到entity的转换方法,使用下划线转大驼峰的方法。propertyNameConvert方法是表字段名到实entity属性名的转换方法,使用大驼峰转小驼峰的方法。

    import com.google.common.base.CaseFormat;

	....

	StrategyConfig strategy = new StrategyConfig();
    
    strategy.setNameConvert(
            new INameConvert() {
                
                @Override
                public String entityNameConvert(TableInfo tableInfo) {
                    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, 	tableInfo.getName());
                }

                @Override
                public String propertyNameConvert(TableField field) {
                    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getName());
                }
            }
    );

3、覆写方法,重新自动生成后发现entity属性的@TableField注解消失 ,setEntityTableFieldAnnotationEnable设为true也不行。通过看源码发现自定义nameCovert后,TableField的convert属性set方法没有执行,导致没有注解。所以,在自定义配置中,强制把每个TableField的convert属性设为true,即可对自定义columnNaming加上@TableField注解。

    
    strategy.setEntityTableFieldAnnotationEnable(true);

	....

    // 自定义配置
    InjectionConfig cfg = new InjectionConfig() {
        @Override
        public void initMap() {
            // to do nothing
        }

        @Override
        public void initTableMap(TableInfo tableInfo) {
            super.initTableMap(tableInfo);
            for (TableField tableField : tableInfo.getFields()) {
                tableField.setConvert(true);
            }
        }

    };

更多推荐

Mybatis Plus 代码生成器 columnNaming 大驼峰转小驼峰