springboot+mybatis返回值为map时,Key值转为驼峰式

在springboot项目中,如果需要将返回的结果集中的字段名转为驼峰式,只需在代码中添加以下代码

resultType="Map"

MapWrapperFactory.java

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
public class MyObjectWrapperFactory implements ObjectWrapperFactory{

    @Override
    public boolean hasWrapperFor(Object object) {
        return object != null && object instanceof Map;
    }
    @Override
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
        return new MyWrapper(metaObject,(Map)object);
    }
    
}

MyWrapper.java

import com.google.common.base.CaseFormat;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;

import java.util.Map;

public class MyWrapper extends MapWrapper {

    public MyWrapper(MetaObject metaObject, Map<String, Object> map) {
        super(metaObject, map);
    }

    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        if(useCamelCaseMapping){
           return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,name);
        }
        return name;
    }
    
}

并在mybatis配置文件中加入

<setting name="mapUnderscoreToCamelCase" value="true"/>  <!-- 驼峰式命名 -->
<objectWrapperFactory type="com.hxps.framework.config.MyObjectWrapperFactory"/>

你可能感兴趣的:(后端,Java)