简体   繁体   English

坚持只更改字段

[英]Persist Only Changed Fields

I have an application which gets data from a database (Mongo) when a user connects, and saves it when a user disconnects and at fixed intervals to reduce the likelihood of data loss if a server goes down. 我有一个应用程序,该应用程序在用户连接时从数据库(Mongo)获取数据,并在用户断开连接时以固定的间隔保存数据,以减少服务器宕机时数据丢失的可能性。 I am using data access objects to save users to the database which updates every field regardless of if it has been changed. 我正在使用数据访问对象将用户保存到数据库,该数据库将更新每个字段,而不管其是否已更改。 This can lead to problems such as when a user joins multiple servers and makes changes on one of them but the changes are overwritten when the user disconnects from another. 这可能会导致出现问题,例如,当用户加入多台服务器并在其中一台服务器上进行更改时,而当用户与另一台服务器断开连接时,更改将被覆盖。

Are there any established ways of persisting only modified fields or any frameworks that do this? 有没有确定的方法仅保留修改后的字段或执行此操作的任何框架? I would rather not use a boolean for every field as I have many fields inside the User object and adding a dirty flag to each of them would increase the class size dramatically. 我宁愿不对每个字段使用布尔值,因为我在User对象中有很多字段,并且向每个字段添加脏标志将极大地增加类的大小。

The steps your application takes: 您的应用程序采取的步骤:

  1. User gets data from MongoDB 用户从MongoDB获取数据

  2. This data get's partially modified 该数据被部分修改

  3. The modifications should get saved 修改应保存

This means: The part of your application that modifies the data should take care of that. 这意味着:应在应用程序中修改数据的部分进行处理。


The Spring team introduces some Diff tool, a few months ago: https://spring.io/blog/2014/10/22/introducing-spring-sync 几个月前,Spring团队引入了一些Diff工具: https//spring.io/blog/2014/10/22/introducing-spring-sync

Using that, you'll get a Patch object, which only contains the changes. 使用它,您将获得一个Patch对象,其中仅包含更改。

Patch patch = Diff.diff(original, modified);

Here's an approach that might work: 这是一种可行的方法:

  1. Object data = mongoClient.getData();
  2. Object modifiedData = modify(data);
  3. Patch patch = Diff.diff(data, modifiedData);

The patch now contains everything that has changed. patch现在包含已更改的所有内容。 Now you must somehow use the internals of the Patch object and map that to MongoDB's $set commands. 现在,您必须以某种方式使用Patch对象的内部并将其映射到MongoDB的$set命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM