首页   >   代码编程   >   JAVA开发

springboot集成mongodb去掉_class字段

在springboot项目中集成了mongodb之后,使用MongoTemplate进行save操作的时候,存储的json字符串中会多一个_class字段,不是什么大问题,但是强迫症患者看着非常的难受。

如下图:

springboot集成mongodb去掉_class字段

解决方案:

package com.zhiri.biz.center.application.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * mongo配置
 *
 * @author SongFei
 * @date 2020/3/9 13:35
 */
@Configuration
@Slf4j
public class MongoConfig {

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException e) {
            // 忽略此异常
            // log.error("mongo配置出错:{}", ExceptionUtils.getStackTrace(e));
        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return mappingConverter;
    }

}

效果图:

springboot集成mongodb去掉_class字段

雨落无影

QQ群Ⅰ: 686430774 (已满)

QQ群Ⅱ: 718410762

QQ群Ⅲ: 638620451 (已满)

QQ群Ⅳ: 474195684

QQ群Ⅴ: 463034360 (已满)

QQ群Ⅵ: 879266502

QQ群Ⅶ: 627786015 (已满)

工作5分钟,吹逼2小时: 855525339 (娱乐消遣,广告狗勿进)

如果文章有帮到你,可以考虑请博主喝杯咖啡!

分享到:

欢迎分享本文,转载请注明出处!

作者:不忘初心

发布时间:2020-05-11

永久地址:https://www.jiweichengzhu.com/article/930c7f5040254044aace8ab6a9bddabb

评论