spring-data-mongodb 在调用 modelRepository.save() 时究竟做了什么?

What exactly spring-data-mongodb do when calls modelRepository.save()?

比如我有一个模型:

@Document(collection = "events")
public class Event {
    @Id
    private String id;
    private String value1;
    private Spring value2;
}

还有服务中的一些代码class:

Event event = eventRepository.findOne("1");
event.setValue1("newValue1");
eventRepository.save(event);

Spring 数据是更新文档的所有字段还是仅更新更改的字段? 在这种情况下,field2 会用旧值更新吗?

我如何打开日志来检查 spring 数据到底做了什么?

logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG

这个只为查询打开日志,不为更新:

016-10-10 09:39:25.938 DEBUG 11417 --- [  restartedMain] o.s.data.mongodb.core.MongoTemplate      : findOne using query: { "_id" : "1"} in db.collection: t87.events
2016-10-10 09:39:25.965 DEBUG 11417 --- [  restartedMain] o.s.data.mongodb.core.MongoTemplate      : Saving DBObject containing fields: [_class, _id, value1, value2]

MongoRepository.save() 在幕后调用 MongoDB db.collection.save。根据 id 的值,它可能会插入/更新插入/替换 整个 文档。

因此,在回答您的问题时:

Does Spring Data update all fields for the document or only changed fields? In this case what's about field2, will it be updated with the old value?

所有字段都已更新(更新),包括具有旧值的字段 2。

为了仅设置字段 1 - 这更有效 - 您必须将 MongoTemplateUpdate$set 运算符结合使用。

为了了解发生了什么,您最好查看 MongoDB 日志以了解如何处理更新操作。有关如何捕获每个写入操作的信息,请参阅 setProfilingLevel;您可能必须通过将分析级别设置为 2 来记录每个操作。之后不要忘记将其关闭。