Mybatis 结果映射下划线转驼峰

mybatis 结果映射下划线转驼峰

Spring Boot 配置:

#下划线转驼峰
mybatis.configuration.map-underscore-to-camel-case=true

mybatis XML 配置


    
    
       
        
    

当resultTpye=map时,以上的配置无效


通过实现ObjectWrapperFactory接口,可以判断当object 是 Map 类型时,返回 true,然后在下面的 getWrapperFor 中返回一个可以处理 key 为驼峰的 Wrapper 类即可。

实现ObjectWrapperFactory

Spring boot 配置

@Configuration
public class MybatisConfig {
    /**
     * mybatis resultType为map时下划线键值转小写驼峰形式插
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());
    }

    
    static class MapWrapperFactory implements ObjectWrapperFactory {
        @Override
        public boolean hasWrapperFor(Object object) {
            return object != null && object instanceof Map;
        }

        @Override
        public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
            return new MyMapWrapper(metaObject, (Map) object);
        }
    }

    static class MyMapWrapper extends MapWrapper {
        MyMapWrapper(MetaObject metaObject, Map map) {
            super(metaObject, map);
        }

        @Override
        public String findProperty(String name, boolean useCamelCaseMapping) {
            if (useCamelCaseMapping
                    && ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z')
                    || name.contains("_"))) {
                return underlineToCamelhump(name);
            }
            return name;
        }

        /**
         * 将下划线风格替换为驼峰风格
         *
         * @param inputString
         * @return
         */
        private String underlineToCamelhump(String inputString) {
            StringBuilder sb = new StringBuilder();

            boolean nextUpperCase = false;
            for (int i = 0; i < inputString.length(); i++) {
                char c = inputString.charAt(i);
                if (c == '_') {
                    if (sb.length() > 0) {
                        nextUpperCase = true;
                    }
                } else {
                    if (nextUpperCase) {
                        sb.append(Character.toUpperCase(c));
                        nextUpperCase = false;
                    } else {
                        sb.append(Character.toLowerCase(c));
                    }
                }
            }
            return sb.toString();
        }
    }
}

还需要配置

#下划线转驼峰
mybatis.configuration.map-underscore-to-camel-case=true

mybatis XML配置

还需要


    
    

你可能感兴趣的:(Mybatis 结果映射下划线转驼峰)