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);
        }
    }
复制代码

 

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

 

posted @   NewSea  阅读(2252)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2016-04-18 Http规范
2011-04-18 内存盘配置IIS临时目录
点击右上角即可分享
微信分享提示