Mybatis返回Map的时候转换为驼峰式

1.首先,我们先继承类 MapWrapper,重写findProperty,通过useCamelCaseMapping来判断是否开启使用驼峰


public class CustomWrapper extends MapWrapper{ public CustomWrapper(MetaObject metaObject, Map<String, Object> map) { super(metaObject, map); } @Override public String findProperty(String name, boolean useCamelCaseMapping) { if(useCamelCaseMapping){ //CaseFormat是引用的 guava库,里面有转换驼峰的,免得自己重复造轮子,pom添加 /** ** <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>24.1-jre</version> </dependency> **/ return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,name); } return name; } }

  

 2. 然后,我们在实现接口 ObjectWrapperFactory,通过包装工厂来创建自定义的包装类,通过hasWrapperFor判断参数不为空,并且类型是Map的时候才使用自己扩展的ObjectWrapper

public 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 CustomWrapper(metaObject,(Map)object);
    }
}

3. 做完以上操作后,我们需要替换下,以前默认的实现,刚好,mybatis-spring-boot上面有告诉我们怎么做,返回一个 ConfigurationCustomizer 的bean,通过匿名内部类实现覆盖默认的MapWrapper的findProperty函数


@Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer mybatisConfigurationCustomizer(){ return new ConfigurationCustomizer() { @Override public void customize(org.apache.ibatis.session.Configuration configuration) { configuration.setObjectWrapperFactory(new MapWrapperFactory()); } }; } }

  

做了以上操作后,我们就将默认的Map映射,的包装类,查找property的部分,变成了自己想要的样子,

最后,我们在 properties或者yml里面加上 mybatis.configuration.map-underscore-to-camel-case=true ,毕竟在CustomerWrapper里面,我们是通过使用这个来控制是否转换驼峰的,最后写个测试用例跑一下,然后会发现,以前db的字段,下划线已经转换成驼峰命名了

posted @ 2019-09-17 15:51  d'l  阅读(2539)  评论(0编辑  收藏  举报