spring data mongo @Field 失效問題

問題

@Field("fs")
public Map<String, Integer> favoriteStickers = new LinkedHashMap<>();

使用MongoTemplate直接爲favoriteStickers字段添加新值key爲STICKER@10002,value爲1時,@Field配置的別名不會被成功映射。java

mongoTemplate.upsert(query(where("uid").is(1), new Update().set("favoriteStickers.STICKER@10002", 1), UserSticker.class);

緣由

MongoTemplate會將執行語句中的key(上面的 uidfavoriteStickers.STICKER@10002 )映射成MongoDB中對應的字段,若是在UserSticker類的定義中有相應的配置則會按配置映射。例如問題字段使用的@Field就是用來配置別名的。 spring

對於favoriteStickers.12 , 會看成favoriteStickers是個數組,12爲被操做的秩,favoriteStickers屬性在UserSticker中有定義能夠成功映射。
對於favoriteStickers.STICKER@10002,會看成是有層級關係。即看成favoriteStickers是一個對象,該對象的定義中有一個STICKER@10002屬性,若是沒有不作映射。favoriteStickers是一個map因此沒法映射。mongodb

重要源碼

org.springframework.data.mongodb.core.convert.QueryMapper#getMappedObject(org.bson.conversions.Bson, org.springframework.data.mongodb.core.mapping.MongoPersistentEntity<?>)方法就是直接用來映射對象的,在這個方法中的代碼Field field = createPropertyField(entity, key, mappingContext);是用來構建字段的映射關係。數組

最終會指向org.springframework.data.mongodb.core.convert.QueryMapper.MetadataBackedField#getPath(java.lang.String)這個方法中出問題的就是PropertyPath path = PropertyPath.from(pathExpression.replaceAll("\\.\\d+", ""), entity.getTypeInformation());這行代碼又會調用org.springframework.data.mapping.PropertyPath#from(java.lang.String, org.springframework.data.util.TypeInformation<?>)app

相關文章
相關標籤/搜索