mongo db 去除 _class 字段

时间:2021-10-16 05:41:26

  1. import org.springframework.beans.factory.BeanFactory;
  2. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.convert.CustomConversions;
  6. import org.springframework.data.mongodb.MongoDbFactory;
  7. import org.springframework.data.mongodb.core.convert.DbRefResolver;
  8. import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
  9. import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  10. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  11. import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
  12.  
  13. /**
  14. * Create by JIUN·LIU at 2018/7/24
  15. */
  16.  
  17. @Configuration
  18. public class MongoConfig {
  19.  
  20. @Bean
  21. public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
  22. DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
  23. MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
  24. try {
  25. mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions. class));
  26. } catch (NoSuchBeanDefinitionException ignore) {
  27. }
  28.  
  29. // Don‘t save _class to mongo
  30. mappingConverter.setTypeMapper(new DefaultMongoTypeMapper( null));
  31.  
  32. return mappingConverter;
  33. }
  34.  
  35. }