我爱编程

关于mongodb子类多态问题的解决方案

2018-03-07  本文已影响0人  杰克家的猫

问题

系统采用spring data+mongodb driver方式进行对象的保存,以及进行相关的序列化以及反序列化。

由于在业务系统设计过程中,需要根据业务不同保存不同的子类,然后展示时也要相应的展示。这就要求mongo在保存时保存完整的数据,并且反序列化时也要能映射到正常的类。

方案

fastjson的JSONType_seeAlso_cn

在fastjson-1.2.11版本中,@JSONType支持seeAlso配置,类似于JAXB中的XmlSeeAlso。

从用法上看基本能满足需求,相比jackson方案比较简洁,也支持隐藏类的展示。不过在序列化类的时候需要加上@type关键字注明类名或者别名。如果要改变关键字,可以使用setDefaultTypeKey来改变。

JavaBean Config

@JSONType(seeAlso={Dog.class, Cat.class})
public static class Animal {
}

@JSONType(typeName = "dog")
public static class Dog extends Animal {
    public String dogName;
}

@JSONType(typeName = "cat")
public static class Cat extends Animal {
    public String catName;
}

Usage

Dog dog = new Dog();
dog.dogName = "dog1001";

String text = JSON.toJSONString(dog, SerializerFeature.WriteClassName);
Assert.assertEquals("{\"@type\":\"dog\",\"dogName\":\"dog1001\"}", text);

jackson的XmlSeeAlso

Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。

可以通过配置多态类型处理,配置相对复杂一点,不过比较灵活。支持使用多种识别码以及识别码可以选择多种方式,包括兄弟属性,扩展属性以及已存在属性等,并且也支持隐藏类名,以及自定义每个类的识别码。

JavaBean Config

public class Car extends Vehicle {
    private int seatingCapacity;
    private double topSpeed;
 
    public Car(String make, String model, int seatingCapacity, double topSpeed) {
        super(make, model);
        this.seatingCapacity = seatingCapacity;
        this.topSpeed = topSpeed;
    }
 
    // no-arg constructor, getters and setters
}

@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME, 
  include = JsonTypeInfo.As.PROPERTY, 
  property = "type")
@JsonSubTypes({ 
  @Type(value = Car.class, name = "car"))
public abstract class Vehicle {
    // fields, constructors, getters and setters
}

Usage

结果

通过对这两种方法的调研,都能满足在序列化以及反序列化时实现子类多态,并且不会有泄漏类名的风险。

发现在mongodb保存类时正常,但是当查询类的内容时,mongodb会直接使用定义的父类进行反序列化。后面通过对mongodb存储以及查询原理的调研发现,mongodb在存储时并不是采用json进行保存,而是采用了BSON这种格式。也就是拓展了JSON的相关信息。

JSON can only represent a subset of the types supported by BSON. To preserve type information, MongoDB adds the following extensions to the JSON format:

* Strict mode. Strict mode representations of BSON types conform to the JSON RFC. Any JSON parser can parse these strict mode representations as key/value pairs; however, only the MongoDB internal JSON parser recognizes the type information conveyed by the format.
* mongo Shell mode. The MongoDB internal JSON parser and the mongo shell can parse this mode.

而mongodb的driver在解析保存的信息时,也是使用的BSON的相关解析方案。于是想是否可以修改相关解析器来实现。发现mongodb在进行序列化以及凡序列化时使用MappingMongoConverter的行为进行定义。于是修改相关定义

@Override
    public MappingMongoConverter mappingMongoConverter() throws Exception {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
        ObjectMapper mapper = new ObjectMapper()
                .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
                .registerModule(new SimpleModule() {
                    {
                        addDeserializer(ObjectId.class, new JsonDeserializer<ObjectId>() {
                            @Override
                            public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                                TreeNode oid = p.readValueAsTree().get("$oid");
                                String string = oid.toString().replaceAll("\"", "");

                                return new ObjectId(string);
                            }
                        });
                    }
                });

        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()) {
            @Override
            public <S> S read(Class<S> clazz, DBObject dbo) {
                String string = JSON.serialize(dbo);
                try {
                    return mapper.readValue(string, clazz);
                } catch (IOException e) {
                    throw new RuntimeException(string, e);
                }
            }

            @Override
            public void write(Object obj, DBObject dbo) {
                String string = null;
                try {
                    string = mapper.writeValueAsString(obj);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(string, e);
                }
                dbo.putAll((DBObject) JSON.parse(string));
            }
        };

        return converter;
    }

然后修改driver相关的Converter,但是测试发现,获取到的bson数据会带有额外的元数据,导致类无法正常反序列化。后面通过查看文档发现,需要增加JsonWriterSettings来对元数据进行处理。

JsonWriterSettings settings = JsonWriterSettings.builder()
                .int64Converter((value, writer) -> writer.writeNumber(value.toString()))
                .objectIdConverter((value,write)->write.writeString(value.toString()))
                .dateTimeConverter((value, writer) -> writer.writeString(value.toString())
                .build();

然后进行相关测试,没发现什么问题。但是后面排查发现,系统还采用了mongoGridFSd的方案,Converter也是采用的此方案,但是bson在转换时,对于binary对象是没有数据展示的,于是修改相关Converter为原来的方案。至此问题解决。

上一篇 下一篇

猜你喜欢

热点阅读