springboot中处理mybatis返回Map时key值的大小写
为了统一不同数据库返回key值大小写不一致的问题,特自定义ObjectWrapperFactory来做统一的处理
创新互联建站坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站建设、网站设计、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的澧县网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!
1,首先自定义MapWrapper
/**
* 将Map的key全部转换为小写
* */
public class MapKeyLowerWrapper extends MapWrapper {
public MapKeyLowerWrapper(MetaObject metaObject, Map map) {
super(metaObject, map);
}
@Override
public String findProperty(String name, boolean useCamelCaseMapping) {
return name==null?"":name.toLowerCase() ;
}
}
2,自定义ObjectWrapperFactory
mybatis默认的ObjectWrapperFactory
public class DefaultObjectWrapperFactory implements ObjectWrapperFactory {
public boolean hasWrapperFor(Object object) {
return false;
}
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
throw new ReflectionException(
"The DefaultObjectWrapperFactory should never be called to provide an 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 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值的大小写
URL网址:http://hbruida.cn/article/jpieei.html