Spring data MongoDb: MappingMongoConverter remove _class

后端 未结 10 946
迷失自我
迷失自我 2020-12-04 21:48

The default MappingMongoConverter adds a custom type key (\"_class\") to each object in the database. So, if I create a Person:

package my.d         


        
10条回答
  •  春和景丽
    2020-12-04 22:27

    If you want to disable _class attribute by default, but preserve polymorfism for specified classes, you can explictly define the type of _class (optional) field by configuing:

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        Map, String> typeMapperMap = new HashMap<>();
        typeMapperMap.put(com.acme.domain.SomeDocument.class, "role");
    
        TypeInformationMapper typeMapper1 = new ConfigurableTypeInformationMapper(typeMapperMap);
    
        MongoTypeMapper typeMapper = new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Arrays.asList(typeMapper1));
        MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
        converter.setTypeMapper(typeMapper);
    
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);
        return mongoTemplate;
    }
    

    This will preserve _class field (or whatever you want to name in construtor) for only specified entities.

    You can also write own TypeInformationMapper for example based on annotations. If you annotate your document by @DocumentType("aliasName") you will keep polymorphism by keeping alias of class.

    I have explained briefly it on my blog, but here is some piece of quick code: https://gist.github.com/athlan/6497c74cc515131e1336

提交回复
热议问题