每次使用mybatis的时候,简单的连表查询,用Map接收的时候,都是像DB定义的字段一样,类似以下 student_name,student_id,没有转换为驼峰,但是又不能因为这一个定义一个javabean来映射数据库字段集合,这样,会有无穷无尽的javabean,完全不是办法。
@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());
}
};
}
}
class MapWrapperFactory implements ObjectWrapperFactory{
@Override
public boolean hasWrapperFor(Object object) {
return object != null && object instanceof Map;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
return new CustomWrapper(metaObject,(Map)object);
}
}
class CustomWrapper extends MapWrapper{
public CustomWrapper(MetaObject metaObject, Map<String, Object> map) {
super(metaObject, map);
}
@Override
public String findProperty(String name, boolean useCamelCaseMapping) {
return getCamelPropertyName(name);
}
/**
*
*
* @date: 2021年10月29日 下午2:22:51
* @type: CustomWrapper
* @Title: getCamelPropertyName
* @Description: 返回驼峰式名字
* @author: 10011372
* @param name
* @return String
*
*/
private String getCamelPropertyName(String name) {
if(name==null||"".equals(name)) {
return name;
}
String[] cols = name.split("_");
StringBuilder buf = new StringBuilder(cols[0].toLowerCase());
if (cols.length > 1) {
for (int i = 1; i < cols.length; i++) {
String str = cols[i];
buf.append(str.substring(0, 1).toUpperCase());
buf.append(str.substring(1).toLowerCase());
}
}
return buf.toString();
}
}