springboot中处理mybatis返回Map时key值的大小写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot中处理mybatis返回Map时key值的大小写相关的知识,希望对你有一定的参考价值。

为了统一不同数据库返回key值大小写不一致的问题,特自定义ObjectWrapperFactory来做统一的处理

1,首先自定义MapWrapper

/**
 * 将Map的key全部转换为小写
 * */
public class MapKeyLowerWrapper extends MapWrapper {

    public MapKeyLowerWrapper(MetaObject metaObject, Map<String, Object> map) {
        super(metaObject, map);
    }
    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        return name==null?"":name.toLowerCase() ;
    }
}

2,自定义ObjectWrapperFactory

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

3,在mybatis的配置中添加 MapWrapperFactory 的配置

@Bean(name = "sqlSessionFactory")
@ConditionalOnBean(name = "dataSource")
public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setObjectWrapperFactory(new MapWrapperFactory());
        bean.setDataSource(dataSource);
        // 添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath*:com/ultrapower/ioss/**/mapper/**/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
}

@Bean("sqlSessionTemplate")
@ConditionalOnBean(name = "sqlSessionFactory")
public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
}

@ConditionalOnBean(name = "dataSource")
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
}

以上是关于springboot中处理mybatis返回Map时key值的大小写的主要内容,如果未能解决你的问题,请参考以下文章

springboot+MyBatis返回Map时值为null的字段会丢失

SpringBoot+MyBatis Plus对Map中Date格式转换的处理

springboot mybatis-plus 调用 sqlserver 的 存储过程 返回值问题

处理Mybatis返回的结果集为Map类型

mybatis返回map类型数据空值字段不显示的解决方法

MyBatis 查询返回数据类型Map,空字段数据不返回