Spring数据MongoDb:MappingMongoConverter删除_class [英] Spring data MongoDb: MappingMongoConverter remove _class

查看:28
本文介绍了Spring数据MongoDb:MappingMongoConverter删除_class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认的MappingMongoConverter 为数据库中的每个对象添加一个自定义类型键(_class").所以,如果我创建一个人:

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

package my.dto;
public class Person {
    String name;
    public Person(String name) {
        this.name = name; 
    }
}

并将其保存到数据库:

MongoOperations ops = new MongoTemplate(new Mongo(), "users");
ops.insert(new Person("Joe"));

mongo 中的结果对象将是:

the resulting object in the mongo will be:

{ "_id" : ObjectId("4e2ca049744e664eba9d1e11"), "_class" : "my.dto.Person", "name" : "Joe" }

问题:

  1. 将 Person 类移到不同的命名空间有什么影响?

  1. What are the implications of moving the Person class into a different namespace?

是否可以不污染_class"键的对象;没有为 Person 类编写唯一的转换器?

Is it possible not to pollute the object with the "_class" key; without writing a unique converter just for the Person class?

推荐答案

所以故事是这样的:我们默认添加类型作为某种提示,以实际实例化哪个类.由于您必须通过管道输入类型以通过 MongoTemplate 将文档读入其中,因此有两种可能的选择:

So here's the story: we add the type by default as some kind of hint what class to instantiate actually. As you have to pipe in a type to read the document into via MongoTemplate anyway there are two possible options:

  1. 您提交一个可以分配实际存储类型的类型.在这种情况下,我们考虑存储类型,将其用于对象创建.这里的经典示例是进行多态查询.假设你有一个抽象类 Contact 和你的 Person.然后,您可以查询 Contact,我们基本上必须确定要实例化的类型.
  2. 另一方面,如果您传入一个完全不同的类型,我们只需编组为该给定类型,而不是实际存储在文档中的类型.这将涵盖您的问题,如果您移动类型会发生什么.
  1. You hand in a type the actual stored type can be assigned to. In that case we consider the stored type, use that for object creation. Classical example here is doing polymorphic queries. Suppose you have an abstract class Contact and your Person. You could then query for Contacts and we essentially have to determine a type to instantiate.
  2. If you - on the other hand - pass in a completely different type we'd simply marshal into that given type, not into the one stored in the document actually. That would cover your question what happens if you move the type.

您可能有兴趣观看这张票,它涵盖了某种可插拔类型映射将类型信息转换为实际类型的策略.这可以简单地用于节省空间的目的,因为您可能希望将长限定类名减少为几个字母的散列.它还允许更复杂的迁移场景,您可能会找到由另一个数据存储客户端生成的完全任意类型键并将它们绑定到 Java 类型.

You might be interested in watching this ticket which covers some kind of pluggable type mapping strategy to turn the type information into an actual type. This can serve simply space saving purposes as you might want to reduce a long qualified class name to a hash of a few letters. It would also allow more complex migration scenarios where you might find completely arbitrary type keys produced by another datastore client and bind those to Java types.

这篇关于Spring数据MongoDb:MappingMongoConverter删除_class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆