Spring Data mongo将空值插入数据库

编程入门 行业动态 更新时间:2024-10-25 14:27:38
本文介绍了Spring Data mongo将空值插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Spring数据mongo向Mongo中插入一条记录,

I am using Spring data mongo to insert a record to Mongo,

这是我的代码 mongoTemplate.save(person,"personCollection");

here is my code mongoTemplate.save(person,"personCollection");

这是我的人对象

public class Person implements Serializable { int age; String address; String name; //Getters and setters including hashcode and equals }

我的地址在此处为空,在将记录插入集合中之后,仅使用年龄和姓名填充数据

my address is null here , after inserting the record in the collection, the data is populated with only age and name

我知道mongodb将null值和noKey视为同一个东西,但是我的要求是甚至填充address:null以使架构保持一致,我该如何使用Spring Data mongo做到这一点

i know that mongodb treats null value and noKey as the same thing, but my requirement is to even populate the address:null to have the schema consistent how do i do this with Spring Data mongo

当前o/p:{"age":21,"name":"john Doe"}

current o/p: {"age":21,"name":"john Doe"}

预期的o/p:{"age":21,"name":"john Doe","address":null}

expected o/p: {"age":21,"name":"john Doe","address":null}

推荐答案

NoSQL DB与RDBMS的工作方式不同. 文档{"age":21,"name":"john Doe"}与{"age":21,"name":"john Doe";"address":null}

NoSQL DB works in a different way compared to RDBMS. the document {"age":21,"name":"john Doe"} is same as {"age":21,"name":"john Doe";"address":null}

最好不要完全存储密钥,而不是将密钥存储为null,这样可以提高对数据库的读取/更新的性能. 但是,如果您的用例由于任何原因仍然需要痛哭null,则可能会将POJO转换为BSONObject,然后将BSONObject保留在MongoDB中.

instead of storing the key's as null better to not store the key at all this improves the performance of your reads/updates against the DB. However, if your usecase still demands to sore null due to whatever the reasons it might be convert your POJO to BSONObject and then persist the BSONObject in the MongoDB.

这里是示例(但是,这只是解决问题的办法)

Here is the example ( but however it will be only a work around to get the things going)

BSONObject personBsonObj = BasicDBObjectBuilder.start() .add("name","John Doe") .add("age",21) .add("address",null).get(); if you are using spring data mongo use mongoTemplate.insert(personBsonObj,"personCollection"); document in the db: db.personCollection.findOne().pretty(); {"age":21,"name":"John Doe";"address":null}*

更多推荐

Spring Data mongo将空值插入数据库

本文发布于:2023-10-25 22:23:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   Data   Spring   将空值   mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!