Java Mongo 自定义序列化笔记

java

1. org.springframework.data.mongodb.repository.support.SimpleMongoRepository.java   insert

2. org.springframework.data.mongodb.core.MongoTemplate.java    toDbObject

3. org.springframework.data.mongodb.core.convert.MappingMongoConverter.java   writeInternal

看到关键代码 :

        MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityType);

writeInternal(obj, dbo, entity);

addCustomTypeKeyIfNecessary(typeHint, obj, dbo);

第2处 writeInternal 出现:

    // Write the properties

entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {

public void doWithPersistentProperty(MongoPersistentProperty prop) {

if (prop.equals(idProperty) || !prop.isWritable()) {

return;

}

Object propertyObj = accessor.getProperty(prop);

if (null != propertyObj) {

if (!conversions.isSimpleType(propertyObj.getClass())) {

writePropertyInternal(propertyObj, dbo, prop);

} else {

writeSimpleInternal(propertyObj, dbo, prop);

}

}

}

});

其中:

entity = org.springframework.data.mapping.model.BasicPersistentEntity

writePropertyInternal 进入非简单属性的写入。

再调用 writeInternal 进行属性写入,可以看出是把 非简单属性当成对象进行循环写入的。 

在写入 id 时, 调用:

org.springframework.data.mongodb.core.convert.QueryMapper.convertId 方法 

/**

* Converts the given raw id value into either {@link ObjectId} or {@link String}.

*

* @param id

* @return

*/

public Object convertId(Object id) {

if (id == null) {

return null;

}

if (id instanceof String) {

return ObjectId.isValid(id.toString()) ? conversionService.convert(id, ObjectId.class) : id;

}

try {

return conversionService.canConvert(id.getClass(), ObjectId.class) ? conversionService.convert(id, ObjectId.class)

: delegateConvertToMongoType(id, null);

} catch (ConversionException o_O) {

return delegateConvertToMongoType(id, null);

}

}

这里并没有区分具体的实体类型,也没有区分属性在根实体的深度,比较简单粗暴。

以上是 Java Mongo 自定义序列化笔记 的全部内容, 来源链接: utcz.com/z/393952.html

回到顶部