Spring Data Mongo 更新对象的非空字段? [英] Spring Data Mongo update non-null fields of object?

查看:58
本文介绍了Spring Data Mongo 更新对象的非空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个只设置了更新字段的 Java 对象,例如(假设有第三个字段 C 未设置):

If I have a Java object with only updated fields set, for example (assume there is a third field C that is not set):

obj.setA(1);obj.setB(2);

是否可以执行仅更新 ABUpdate 操作?看来我对 Spring Data 的唯一选择是使用 save() (这会将数据库中 C 的值覆盖为 null),或者使用 update(),这需要我为对象中的每个字段构造一个带有 set() 语句的 Update 对象,以及作为硬编码 Mongo 字段名称.基本上我正在寻找的是可以执行此更新操作的东西:

Is it possible to perform an Update operation that only updates A and B? It appears my only options with Spring Data are to use save() (which would overwrite the value for C in the database to null), or use update(), which requires me to construct an Update object with a set() statement for each field in the object, as well as hardcode Mongo field names. Essentially what I'm looking for is something that would do this update operation:

$set:{'a':1,'b':2}

我正在尝试使用反射来尝试执行此操作(查看提供的解决方案 here),这可能有用,但似乎有点hacky.如果 Spring Data 以某种方式支持这一点,我宁愿这样做.

I was messing around a bit with Reflection to try and do this (looking at the solutions offered here), which could potentially work, but it seems a bit hacky. If Spring Data supports this somehow, I'd rather do that.

推荐答案

o.s.d.m.core.query.Update 正是为了这个目的.
来自 参考文档:

There is o.s.d.m.core.query.Update for exactly that purpose.
From the reference documentation:

// query: { "name" : "Joe" }
// update: { "$set" : { "age" : 35} }
mongoOps.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);

这篇关于Spring Data Mongo 更新对象的非空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆