MyBatis返回Map键值对数据Key值改小写

--场景一:
select code,name,addr from users
---场景二:
select * from users

使用MyBatis查询且resultType=Map时,如果未做任何配置,以上两个SQL查询结果均如下:

[{
	CODE: '1',
	NAME: '张三',
	ADDR: '上海'
}]

我希望将键值改为小写:

方法一:设置返回字段的别名

对于场景一,我们可以给每个查询字段加个别名,如下:

select 
	code as "code",
	name as "name",
	addr as "addr"
from users

但加别名的方式不适用于场景二。

方法二:通用方法(推荐)

  • 步骤一:创建类MapKeyLowerWrapper.java,继承MapWrapper。该类将查询结果转换成Map。
package com.example.demo.filter;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import java.util.Map;
/**
 * 将Map的key全部转换为小写
 */
public class MapKeyLowerWrapper extends MapWrapper {

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

    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        return name == null ? "" : name.toLowerCase();
    }
}

步骤二:创建类MapWrapperFactory.java。该类引用调用刚创建的自定义转换类MapKeyLowerWrapper

package com.example.demo.filter;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;

import java.util.Map;

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);
    }
}

步骤三:创建类ObjectWrapperFactoryConverter.java

package com.example.demo.filter;

import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;


@Component
@ConfigurationPropertiesBinding
public class ObjectWrapperFactoryConverter implements Converter<String, ObjectWrapperFactory> {
    @Override
    public ObjectWrapperFactory convert(String source) {
        try {
            return (ObjectWrapperFactory) Class.forName(source).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

步骤四:在yml中添加 MapWrapperFactory 的配置

#mybatis配置
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    object-wrapper-factory: com.example.demo.filter.MapWrapperFactory

重启即可。

你可能感兴趣的:(mybatis)