為了統(tǒng)一不同數(shù)據(jù)庫返回key值大小寫不一致的問題,特自定義ObjectWrapperFactory來做統(tǒng)一的處理
創(chuàng)新互聯(lián)建站堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的澧縣網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
1,首先自定義MapWrapper
/**
* 將Map的key全部轉(zhuǎn)換為小寫
* */
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默認(rèn)的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;
}