Java Mongo 自定義序列化筆記


從insert方法入手

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);
        }
    }

 

這里並沒有區分具體的實體類型,也沒有區分屬性在根實體的深度,比較簡單粗暴。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM