mybatis Map查詢結果下劃線轉峯坨

添加一個配置類MybatisCamelConfig 即可

package com.fpi.notify.config;

import com.google.common.base.CaseFormat;
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.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * mybatis查詢Map返回值下劃線轉峯坨
 * @author xingxing_yuan
 * @since 2020-02-18 13:47
 */
@Configuration
public class MybatisCamelConfig {
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
//            使用自定義的解析器工廠
        return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());
    }

    /**
     * 實現工廠
     */
    static class MapWrapperFactory implements ObjectWrapperFactory {
        @Override
        public boolean hasWrapperFor(Object object) {
//        判斷是Map就使用該解析
            return object instanceof Map;
        }

        @Override
        public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
//        將默認的解析器替換成峯坨轉換
            return new CamelWrapper(metaObject, (Map) object);
        }
    }

    /**
     * 重寫轉換器;添加轉換方法
     */
    static class CamelWrapper extends MapWrapper {

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

        /**
         * mybatis查詢結果下劃線轉峯坨
         *
         * @param name
         * @param useCamelCaseMapping 是否進行轉換。yaml 中配置map-underscore-to-camel-case=true
         * @return
         */
        @Override
        public String findProperty(String name, boolean useCamelCaseMapping) {
            if (useCamelCaseMapping) {
//                使用guava的轉換方法,覆蓋Map的默認返回值
                return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
            }
            return name;
        }

    }
}

具體的實現原理參考

https://blog.csdn.net/weixin_37848710/article/details/83995825

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章