Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot & MongoDB how to remove the '_class' column?

When inserting data into MongoDB Spring Data is adding a custom "_class" column, is there a way to eliminate the "class" column when using Spring Boot & MongoDB?

Or do i need to create a custom type mapper?

Any hints or advice?

like image 561
Marco Avatar asked May 07 '14 12:05

Marco


3 Answers

A more up to date answer to that question, working with embedded mongo db for test cases: I quote from http://mwakram.blogspot.fr/2017/01/remove-class-from-mongo-documents.html

Spring Data MongoDB adds _class in the mongo documents to handle polymorphic behavior of java inheritance. If you want to remove _class just drop following Config class in your code.

package com.waseem.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
public class MongoConfig {

 @Autowired MongoDbFactory mongoDbFactory;
 @Autowired MongoMappingContext mongoMappingContext;

 @Bean
 public MappingMongoConverter mappingMongoConverter() {

  DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
  MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
  converter.setTypeMapper(new DefaultMongoTypeMapper(null));

  return converter;
 }
}
like image 184
Jeremie Avatar answered Oct 29 '22 13:10

Jeremie


Dave's answer is correct. However, we generally recommend not do this (that's why it's enabled by default in the first place) as you effectively throw away to persist type hierarchies or even a simple property set to e.g. Object. Assume the following type:

@Document
class MyDocument {

  private Object object;
}

If you now set object to a value, it will be happily persisted but there's no way you can read the value back into it's original type.

like image 39
Oliver Drotbohm Avatar answered Oct 29 '22 15:10

Oliver Drotbohm


Here is a slightly simpler approach:

@Configuration
public class MongoDBConfig implements InitializingBean {

    @Autowired
    @Lazy
    private MappingMongoConverter mappingMongoConverter;

    @Override
    public void afterPropertiesSet() throws Exception {
        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    }
}
like image 9
RZet Avatar answered Oct 29 '22 13:10

RZet