zoukankan      html  css  js  c++  java
  • 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);
            }
        }

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

  • 相关阅读:
    JFinal框架
    shiro认证登录实现
    linux常用的命令
    zookeeper部署到linux操作步骤
    java的冒泡排序
    软件设计的七大原则
    vue知识点整理
    JVM垃圾回收算法
    Sql Server删库了怎么办?跑路是不可能跑路的
    Linux--find用法
  • 原文地址:https://www.cnblogs.com/newsea/p/6725765.html
Copyright © 2011-2022 走看看