spring+mybatis 返回值为map时返回驼峰命名
<resultMap id ="UserInfoMap" type="com.example.mybaitsxml.dao.entity.User"> <result column="name_" property="name"/> <result column="sex" property="sex"/> <result column="age" property="age"/> <result column="class_no" property="classNo"/> </resultMap> <resultMap id ="UserInfoMap" type="map"> <result column="name_" property="name"/> <result column="sex" property="sex"/> <result column="age" property="age"/> <result column="class_no" property="classNo"/> </resultMap> <select id="find" parameterType="map' resultType="UserInfoMap"> </select>
第二种:
application配置:
map-underscore-to-camel-case: true
mybatis-plus: mapper-locations: classpath*:org/jeecg/modules/**/xml/*Mapper.xml global-config: # 关闭MP3.0自带的banner banner: false db-config: #主键类型 0:"数据库ID自增",1:"该类型为未设置主键类型", 2:"用户输入ID",3:"全局唯一ID (数字类型唯一ID)", 4:"全局唯一ID UUID",5:"字符串全局唯一ID (idWorker 的字符串表示)"; id-type: 4 # 默认数据库表下划线命名 table-underline: true configuration: #返回Map的时候,将Map内的Key转换为驼峰的命名表达式 map-underscore-to-camel-case: true # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
新建工具类:
package org.jeecg.config.mybatis; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.wrapper.MapWrapper; import org.apache.ibatis.reflection.wrapper.ObjectWrapper; import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory()); } static 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 MyMapWrapper(metaObject, (Map) object); } } static class MyMapWrapper extends MapWrapper { MyMapWrapper(MetaObject metaObject, Map<String, Object> map) { super(metaObject, map); } @Override public String findProperty(String name, boolean useCamelCaseMapping) { if (useCamelCaseMapping && ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') || name.contains("_"))) { return underlineToCamelhump(name); } return name; } /** * 将下划线风格替换为驼峰风格 * * @param inputString * @return */ private String underlineToCamelhump(String inputString) { StringBuilder sb = new StringBuilder(); boolean nextUpperCase = false; for (int i = 0; i < inputString.length(); i++) { char c = inputString.charAt(i); if (c == '_') { if (sb.length() > 0) { nextUpperCase = true; } } else { if (nextUpperCase) { sb.append(Character.toUpperCase(c)); nextUpperCase = false; } else { sb.append(Character.toLowerCase(c)); } } } return sb.toString(); } } }